6

I have been using React state to maintain some data. For ints and strings it's working well, but unfortunately arrays are not working.

In my component constructor, I have

constructor(props) {
    super(props);

    this.state = {
        terms: 5,
        myArray: []
    }

and then, I am trying to maintain it in componentDidUpdate

componentDidUpdate() {
    this.state = {
        terms: this.state.terms,
        myArray: this.state.myArray
    }

but myArray: this.state.myArray is not working. However terms: this.state.terms is working perfectly.

Can someone help!

4
  • 1
    why do you want to setState in componentDidUpdate method ?? and one more thing what do you mean by not working, r u trying to update the array ? Commented Mar 31, 2017 at 14:17
  • and also you should use this.setState() to update state Commented Mar 31, 2017 at 14:18
  • After rendering components, I have to change other state values. Commented Mar 31, 2017 at 14:19
  • @ Mayank Shukla Actually, I am re initialising state due to some reason, Anyhow never mind. I resolved my problem. But thank you for your timely reply. I really appreciate. Commented Mar 31, 2017 at 16:03

3 Answers 3

4

Issue is you are updating the state value in a wrong way, Update the state value like this:

this.setState({
     terms: this.state.terms,
     myArray : this.state.myArray
});

As per DOC:

Never mutate this.state directly, as calling setState() afterwards may replace the mutation you made. Treat this.state as if it were immutable.

Update the state array like this, first create a copy of that by using slice(), then do the change and use setState to update:

let arr = this.state.myarr.slice();
arr.push('data');
this.setState({arr});
Sign up to request clarification or add additional context in comments.

Comments

2

You cannot set state directly like that since its an array you will have to append the value or else push the value.

try something like

var newArray = this.state.myArray.slice();    
newArray.push("new value");   
this.setState({myArray:newArray})

here i sliced to make it immutable.

Comments

1

You cannot use this.state with purpose to update state, you have to use:

this.setState(newStateObject);

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.