Skip to content
Advertisement

React state returns an array of functions [closed]

I am building an app that uses an API and I’m calling 151 API calls and then hoping to return each of those results as an object to my state array.

The code is below and when I log the results I get an array of ‘newPokemon’ callback functions and not the data.

const fetchPokemon = useCallback(async () => {
    setLoading(true)
    try {
      for (let i = 0; i < numbers.length; i++) {
        const response = await fetch(`${url}${numbers[i]}`)
        const data = await response.json()
        const newPokemon = () => {
          const {
            name,
            order,
            height,
          } = data
          return {
            name,
            order,
            height,
          }
        }
        setPokemon((prevState) => [...prevState, newPokemon])
      }
    } catch (error) {
      console.log(error)
      setLoading(false)
    }
  }, [])

Could anyone help? If I call setPokemon as below the API call and the data works but is overwritten on every iteration so the state will only ever be one object at the end of the loop not the full dataset. i have tried multiple syntax of setting the state so far to no avail

setPokemon(newPokemon)

Thank you in advance

Advertisement

Answer

You declared a new function named newPokemon and then insert it into the state, this is why you get array of functions inside the state. you need to insert the function execution result instead: setPokemon((prevState) => [...prevState, newPokemon()])

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement