skip to Main Content

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


  1. 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:

    const fetchCities = ()=>{
        return fetch('cities.json');
    }
    
    async function main(){
        try {
            const res = await fetchCities();
            const data = await res.json();
            // handle the data here, this will work only after the data arrival
            console.log(data);
        } catch (err) {
            console.log(err);
        }
    }
    main();
    

    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:

    const fetchCities = ()=>{
        return fetch('cities.json');
    }
    function main(){
        fetchCities()
        .then(res => res.json())
        .then(data => {
            // handle the data here, all you code should be here
        })
        .catch (err => console.log(err));
    }
    main();
    
    Login or Signup to reply.
  2. You could do this very simply with async/await like this:

    const fetchCities = async () => {
      let cities = await fetch('cities.json');
      return cities.json();
    };
    
    let cities = await fetchCities();
    console.log(cities);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search