h_h
h_h

Reputation: 1231

React JS maintain array inside state

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!

Upvotes: 6

Views: 4054

Answers (3)

Mayank Shukla
Mayank Shukla

Reputation: 104369

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

Upvotes: 4

TRomesh
TRomesh

Reputation: 4471

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.

Upvotes: 2

cn0047
cn0047

Reputation: 17061

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

this.setState(newStateObject);

Upvotes: 1

Related Questions