1

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?

0

2 Answers 2

2

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 })
Sign up to request clarification or add additional context in comments.

1 Comment

this could work too.. this.setState({ data2: Object.assign({}, this.state.data2, { nodes: [...this.state.data2.nodes, {id: 'input1'}, {id: 'input2'}] }) })
1

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"}])});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.