Saving fetched JSON into variable
let jsondata;
fetch(url).then(
function(u){ return u.json();}
).then(
function(json){
jsondata = json;
}
)
Basically you need to assign your jsondata
variable once the promise resolves with the actual data. Currently, you're assigning the entire promise to your jsondata
variable which is not what you want.
The fetch API is Promise based and will always return a new Promise either resolved or rejected. You have multiple options to return the result.
Async/Await
async function getData(url) {
const response = await fetch(url);
return response.json();
}
const data = await getData(url);
console.log({ data })
Callback
function getData(url, cb) {
fetch(url)
.then(response => response.json())
.then(result => cb(result));
}
getData(url, (data) => console.log({ data }))