Search code examples
javascriptreactjsreact-nativesetstate

How to correctly change state of a multiple nested array of objects in React?


What would be the best way to change the state of multiple nested arrays of objects in React? Let's see the example below: I have a component that will display the top playlist for each genre. I have a property genre which is an array of objects and each object has a property songs which is also an array of objects. If I want to change the song named Soldier of Fortune to Child in Time (Let's suppose in Change function as parameters I have indexes of Song and Genre already provided from the UI change). How can I access multiple levels of nested objects and not mutate the state?

this.state = {
    title: 'Top playlists',
    genres: [
      {
        genreName: 'pop',
        followers: 2456,
        songs: [
          {
            title: 'Soldier of fortune',
            author: 'Deep Purple',
          },
        ],
      },
    ],
  };

handleChangeSongName = (e, genreIndex, songIndex) => {
    // genreIndex = 0;
    // songIndex = 0;
    // e.target.name = title;
    // e.target.value = "Child in time"  
    ...What to do here?
  }


Solution

  • you can modify your handleChangeSongName function to this:

      handleChangeSongName = (e, genreIndex, songIndex) => {
    // genreIndex = 0;
    // songIndex = 0;
    // e.target.name = title;
    // e.target.value = "Child in time"  
    this.setState((prevState) => {
      let temp = {
        ...prevState,
        genres: [...prevState.genres]
      }
    
      // change title "Soldier of fortune" to "Child in time"
      temp.genres[genreIndex].songs[songIndex][e.target.name] = e.target.value
    
      return temp
    })
    

    }