I’m facing a probably super easy to solve problem regarding fetching.
I’d like to fetch some json datas and store it in a variable to access it later.
The problem is that I always ends up getting undefined in my variable. What’s the way to do to deal with that kind of data storing ?
Here’s my code.
const fetchCities = () => {
fetch('cities.json')
.then(response => response.json())
.then(data => {
return data;
});
}
let cities = fetchCities();
console.log(cities)
Already looked up for answers but couldn’t find a way to do. Thanks !
2
Answers
Sending a fetch request takes time, so the
console.log
works before the data arrives.The best way to deal with fetch is using async functions and await like so:
Note:
await
can only be used in async functions, that’s the main purpose of the main function.Or if you want to use
.then
:You could do this very simply with
async/await
like this: