Api call useEffect hook

The goal is to build the data before displaying to the user, i want to build up the state like this:

// [
//  {
//   name:  ""
//   image_url: ""
//   number:""
//   types: []
//  },
// ......
// ]

My homework is:

is after fetching the first time. it will return an array then use that array in a “for of” loop using an asyc code to do the second fetch and build the data

why its not working?:

 const [pokemonData, setPokemonData] = useState([]);
  useEffect(() => {
    async function getData() {
      const res = await fetch("https://pokeapi.co/api/v2/pokemon");
      const pokemons = await res.json();
      const { results } = pokemons;
      return callback(results);
    }
    getData();

    const callback = (res) => {
      let imgUrl = "https://pokeres.bastionbot.org/images/pokemon/";
      console.log(res, "cb");
      for (const [index, value] of res.entries()) {
        console.log(index, value);
        async function getFollowUp() {
          const res = await fetch(value.url);
          const pokemon = await res.json().then((data) => {
            return {
              types: [data.types],
              name: data.name,
              image_url: imgUrl + index + 1,
              number: index + 1,
            };
          });
          secondCallback(pokemon);
        }
        getFollowUp();
        const secondCallback = (data) => {
          // setPokemonData((prevState) => ({
          //   ...prevState,
          //   data,
          // }));
          setPokemonData(data);
        };
      }
    };
  }, []);

my last question, what if the name property was not found on the second fetch, it is in this case… but pretend it isnt… what would you do differently to the code, see here result of first fetch:

the only thing I have in state is the second to last element from the second fetch call,

uncommenting this line only sets the last element as a data prop in the state…
// setPokemonData((prevState) => ({ // ...prevState, // data, // })); setPokemonData(data);

for anyone who has this same quesion, ive solved for this the answer is to change the line here in the second callback:

       const secondCallback = (data) => {
          console.log(data, "data in second callback");
          setPokemonData((oldArray) => [...oldArray, data]);

          // setPokemonData((prevState) => ({
          //   ...prevState,
          //   data,
          // }));

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