Konstantinos Ks
Konstantinos Ks

Reputation: 79

setState in nested arrays in react

I have a React state object with two arrays inside of it.

this.state = {
  data2: {
    nodes: [{id: 'input'}],
    links: []
  },
};

I want to add new values to these arrays after some user action but I haven't figured out the right way. So far I have attempted something like this:

this.setState([...this.state.data2, {nodes: [...this.state.nodes,{ id: 'input2'}]}]);

Any ideas on how should I implement this?

Upvotes: 1

Views: 2874

Answers (2)

Yahya Ahmed
Yahya Ahmed

Reputation: 347

I would recommend something like this

this.state = { 
    data2: {
    nodes: [],
    links: []
  },
};

when you set your state you dont have to use the this keyword inside the setState function

this.setState({ data2:{ nodes: [{id:'input1'},{id:'input2'}]} })

you can push objects in nodes array too

let temp = data2
temp.nodes.push({id:'input3'})
this.setState({ data2:temp })

Upvotes: 2

Ankur Kedia
Ankur Kedia

Reputation: 3873

It can be done in two simple ways. One which you did, using spread operator. Something like this,

this.setState({data2: {...this.state.data2, nodes: [{id: "input1"}]} });

Or you can use [Object.assign()][1] like this,

this.setState({data2: Object.assign({}, this.state.data2, nodes: [{id: "input1"}])});

Upvotes: 1

Related Questions