How to change state of complex objects in React?

1

I have the following object:

obj = {
  title: "obj1",
  tab: [{
     title: "titulo da tab 1",
     card: [{
        title: "card1",
        url: "url",
        image: "image"
     },
     { 
        title: "card2",
        url: "url",
        image: "image"
     }]

  },
  {
     title: "titulo da tab 2",
     card: [{
        title: "card3",
        url: "url",
        image: "image"
     },
     { 
        title: "card4",
        url: "url",
        image: "image"
     }]

  }
]

}

When I want to change the state of a variable in react use

setState({obj1: data})

When I want to change the state of a property of an obj I use:

setState({obj1: {...this.state.obj1, title: "new title"} })

But my difficulty is:

  • How to change the title of a card in the obj?
  • How to change a tab title in obj?
asked by anonymous 13.08.2018 / 21:32

1 answer

1

For large nested structure I think preferable:

  • Replicate the state to a local object, in order to preserve the original.
  • Change what you want in this object
  • Call setState with this new state

Example:

const novoEstado = Object.assign({}, this.state);
novoEstado.obj1.tab[1].card[0].title = 'Novo titulo de um card';
novoEstado.obj1.tab[0].title = 'Novo titulo para o primeiro tab';
this.setState(novoEstado);

Object.assign replicates the state it has in a new object, preserving the original and following what the documentation indicates not to change the state directly.

    
13.08.2018 / 21:49