How to return the data from fetch API to a variable or a const

I am trying to fetch the data from a json url and post it to a variable
let tempData = getTemp();

async function getTemp(){await
fetch(‘https://jsonplaceholder.typicode.com/users’)
.then(function(response) {
return response.json();
})

}

console.log(tempData);

This doesn’t work. It prints the promise object on the console. when we expand that object, we have the result. But i just need the result alone. In react we get the data and use useState hook to set the state with the data. but, what if i use HTML and get the data from json URL on a normal javascript function

Hi I think the issue is because you are calling getTemp() then trying to print the result immediately but its not ready yet. You could try the code below:

async function fetchData() {
    const response = await fetch('https://jsonplaceholder.typicode.com/users');
    tempData = await response.json();
    console.log(tempData);
}

fetchData();
1 Like

This helps. but isn’t there a way to collect all the fetched data into a variable and display it whenever it is required ?