I was trying to call on the Pokemon API when I ran into this problem.
I wanted to pull in all the Pokemon and display them in cards. I used useState to set my pokemons variable to an empty array by default.
const [pokemons, setPokemons] = useState([]);
I used useEffect and axios to pull the data from the API
useEffect(() => {
axios
.get(“https://pokeapi.co/api/v2/pokemon/?limit=25")
.then(res => {
setPokemons(res.data);
console.log(res.data);
})
.catch((err) => {
console.log(err);
});
}, []);
When I ran the code, I got this error
Apparently, before I even got the data from the API, it was trying to use the apply method on my undefined array.
But wait, didn’t I initialize this array to an empty array in useState?
const [pokemons, setPokemons] = useState([]);
And it looked like I was retrieving the data from the API just fine
So why was this happening?
Well, let’s look at that JSON response. Here’s a screenshot of the response on Postman. It’s returning an object and the array is one of the properties of that object.
That’s when it hit me. The response was returning an object, not an array, so my initializing pokemons to an empty array did nothing, because [].results was still undefined.
So I made a modification.
I needed to initialize the results property to an empty array, so I did this
const [pokemons, setPokemons] = useState({results: []});
I made an object with the results property set to an empty array.
And now the app works!
This is probably not the most elegant solution, but it works. Do you have a better way to handle this? Feel free to comment!
(I’m using the PokeAPI if anyone’s interested.)