Search code examples
reactjsaxiosspotifymap-function

Can't map fetched data in react js (Cannot read properties of undefined (reading 'map'))


I have fetched data from Spotify API and it displays in console but when I try to return data inpage it says map is not defined I use useState([]) and pass it to array if I am saying it right way:

const [track, setTrack] = useState([])
const getRecommendation = async (e) => {
  e.preventDefault()
  const {data} = await axios.get("https://api.spotify.com/v1/recommendations", {
    headers: {
      Authorization: `Bearer ${token}`
    },
    params: {
      limit: '10',
      seed_artists: '4NHQUGzhtTLFvgF5SZesLK',
      seed_genres: 'rock,pop,metal',
      seed_tracks: '0c6xIDDpzE81m2q797ordA'
    }
  })
  setTrack(data.tracks.item)
  console.log(data);
  
}
const renderTracks = () => {
  return track.map(tracks => {
    return (
       <h1 className='track-name'>
       {tracks.name}
       </h1>
      )
  }) 
}

Here in console:

enter image description here

Any advice?


Solution

  • According to this:

    console.log(data);
    

    The data object has a property called tracks which is an array. Which means this:

    setTrack(data.tracks.item);
    

    Is setting the state to undefined, because there is no .item property on an array.

    This implies that you're expecting to iterate over an array:

    return track.map(tracks => {
    

    So set the state to the array, not some property you expect to be on the array:

    setTrack(data.tracks);
    

    As an aside, the plurality in your names is backwards. This is going to cause confusion for you (if it hasn't already). Consider the semantics of this:

    return track.map(tracks => {
    

    In this line of code, track is an array and tracks is a single object. That's not how plurality works. Rename your variables to accurately reflect what they contain:

    const [tracks, setTracks] = useState([]);
    

    and:

    setTracks(data.tracks);
    

    and:

    return tracks.map(track => {
    

    This could very well be what caused your problem in the first place, since setTrack implies that it's expecting a single object and data.tracks is an array.

    Keep your variable names consistent and meaningful and your code will be much easier to read and understand.