0

I have a state, with a nested object inside it. If I update one value, the other is getting override, I want to hold the previous as well as new value.

this is what I tried:

Default Phase:

state = {
 custom: {
  data: null,
  categories: null
 },
 index: 0
}

Updating Phase:

this.setState({ ...this.state.custom, custom: { data: data } });
this.setState({ ...this.state.custom, custom: { categories: categories } });
this.setState({ ...this.state.custom, index: index });

So what is happening is the values are getting override with the last value of state update.

Expected output:

state = {
 custom: {
  data: new updated value,
  categories: new updated value
 },
 index: new updated value
}

1 Answers1

0

Try this

this.setState({ custom: { ...this.state.custom, data: data, categories:categories }, index: index });
N. Solomon
  • 140
  • 2
  • 7