Search code examples
javascriptfetch-api

How to parse JSON results properly


I am currently working with the PokeAPI, I am doing fetch requests to recieve back the JSON at a given endpoint, then trying to parse and return it. The function for doing this can be found here:

function getPokemon(id){

    pokemonData = {
        name:"",
        image:"",
        id:id,
        description:""
    }
    
    // Documentation https://pokeapi.co/docs/v2#pokemon-species
    fetch(`https://pokeapi.co/api/v2/pokemon-species/${id}/`)
      .then((response) => response.json())
          .then((data) => {
        
            pokemonData.description = data.flavor_text_entries[0].flavor_text.toString()
            
          }
        )
    
    // Documentation: https://pokeapi.co/docs/v2#pokemon
    fetch(`https://pokeapi.co/api/v2/pokemon/${id}/`)
      .then((response) => response.json())
          .then((data) => {
        
            pokemonData["image"] = data.sprites.other["official-artwork"].front_default.toString()
            pokemonData["name"] = data.name.toString()
            
          }
        )

    return pokemonData
}

Once the data is returned trying to access attributes are blank, but the object displays the correct info:

enter image description here

I'm not sure what seems to be going wrong here. I have tried every different attribute access format data.name vs data["name"] and none seem to make a difference. Any help would be appreciated


Solution

  • Your own answer is correct in the way that it solves your problem.
    But it doesn't fully utilize async / await and promises.

    Using await on both fetch calls makes the code run the requests one by one. You can make this faster by letting both fetch calls run in parallel and wait for both to finish with Promise.all().

    After both requests as are finished, create your pokemonData object and return it based on the data from both sets.

    async function getPokemon(id) {
      const speciesRequest = fetch(`https://pokeapi.co/api/v2/pokemon-species/${id}/`)
        .then((response) => response.json())
        
      const pokemonRequest fetch(`https://pokeapi.co/api/v2/pokemon/${id}/`)
        .then((response) => response.json())
      
      try {
        const [speciesData, pokemonData] = await Promise.all([speciesRequest, pokemonRequest]);
    
        return ({
          id,
          image: pokemonData.sprites.other["official-artwork"].front_default,
          name: pokemonData.name,
          description: speciesData.flavor_text_entries[0].flavor_text.toString()
        });
      catch (error) {
        return Promise.reject(error);
      }
    }