Updating an array with an API response using useState

Viewed 15

I'm working in React and want to update an array I have with the response from an API request to the musixmatch API. Basically, albums.tracks.gets returns an array of all the songs on a certain album. This is the res.data response that I'm getting back from the API request I'm trying to basically load this entire album_list 'array' into an array called albums using a useState hook. What is the best approach here? This is the code that I have written to update albums Currently, I'm defining albums as a state and trying to use setAlbums to update it. I am trying to load the entire album_list array and load all of the names/album_ids into the array. Right now, when I console.log(albums) the console just prints out [], an empty array. Is there a way to store both in some sort of dict? Or would I have to store one or the other in a simple array. Thank you!

1 Answers

There is two issues in the second picture, which may lead to the empty array:

  1. You are console.logging res.data.message.body.album_lis but adding res.data.message.body.album_list to your state variable.
  2. Be aware that setState is asynchronous (see this question) , you could try useEffect to console.log albums.
Related