Get data from API JavaScript 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 api tutorial
fetch('https://api.github.com/users/manishmshiva', {
method: "GET",
headers: {"Content-type": "application/json;charset=UTF-8"}
})
.then(response => response.json())
.then(json => console.log(json));
.catch(err => console.log(err));
Example 3: get data from api in javascript
const GetData = [];
useEffect(() => {
fetch(API_URL)
.then((res) => res.json())
.then((data) => {
GetModesData.push(...data);
setDataState(GetData.map((d) => d.modeName));
});
}, []);
Example 4: fetch api map
const GetData = [];
useEffect(() => {
fetch(API_URL)
.then((res) => res.json())
.then((data) => {
GetModesData.push(...data);
setDataState(GetData.map((d) => d.modeName));
});
}, []);
Example 5: 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;
});