fetch API data javascript and return to a variable code example
Example 1: get data from fetch api into variable
<script>
function getFromAPI(url, callback){
var obj;
fetch(url)
.then(res => res.json())
.then(data => obj = data)
.then(() => callback(obj))
}
getFromAPI('https://jsonplaceholder.typicode.com/posts', getData);
function getData(arrOfObjs){
var results = "";
arrOfObjs.forEach( (x) => {
results += "<p> Id: " + x.id + "<ul>"
Object.keys(x).forEach( (p) => {
results += "<li>" + (p + ": " + x[p]) + "</li>";
});
results += "</ul> </p> <hr>"
})
results += "";
document.getElementById("myDiv").innerHTML = results;
}
</script>
Example 2: fetch get data js
var myHeaders = new Headers();
var myInit = { method: 'GET',
headers: myHeaders,
mode: 'cors',
cache: 'default' };
fetch('flowers.jpg',myInit)
.then(function(response) {
return response.blob();
})
.then(function(myBlob) {
var objectURL = URL.createObjectURL(myBlob);
myImage.src = objectURL;
});