How to assign variable to fetch result data?

var jsonData;
fetch('').then(response=> response.json()).then(data=>{jsonData=data;

Please help in the Dev Tool console jsonData is not return the fetched data but return undefined

It will return the data but you are calling console.log before the data is actually returned since the console.log statement runs before the fetch is actually completed and thus jsonData is undefined at the time console.log is executed.

Look at the first example on the MDN fetch documentation for how to properly do it. If you want to console.log the fetched data you have to put it inside of the last then method. Or you could use async/await which may make the code a little more readable.

And you have some syntax errors in the code you pasted above.

1 Like

your " var jsonData" is undefined because it needs an equal (=) instead of a semicolon(;).
var jsonData = (needs to equal something to be defined. ("="))
var jsonData; (semicolon at the end of an undeclared variable will always return “undefined”)

fetch('').then(response=> response.json()).then(data=>{jsonData=data;
console.log(jsonData);     ```

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.