How to change the state of complex objects in React?

Asked

Viewed 885 times

3

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 status of a variable in the use React

setState({obj1: data})

when I want to change the status of an obj property I use:

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

but my difficulty is:

  • How to change the title of a card in obj?
  • How to change a tab title in obj?

1 answer

3


For widely nested structure I find it preferable:

  • Replicate the state on a local object in order to preserve the original.
  • Change what you want in this object
  • Call the setState with that 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);

The Object.assign replicates the state it has on a new object, preserving the original and following what the documentation indicates of not changing the state directly.

  • is this.state same or is this.state.obj1 ? on line 1

  • @Juliohenrique It was my mistake, I didn’t notice that the state has as its root object the obj1, but the idea is to capture the whole state which is easier. I will adjust

Browser other questions tagged

You are not signed in. Login or sign up in order to post.