Search code examples
reactjssetstate

React how to delete properties from state


I'm trying to replace whole state or at least delete all properties from it.

Before react 16 I just called these two lines

this.state = {}
this.forceUpdate()

With update to react 16, this didn't work anymore. Currently I have this workaround in shouldComponentUpdate Method:

for (let prop in nextState) { 
    if (nextState.hasOwnProperty(prop)) { 
        delete nextState[prop]; 
    } 
}

But this 'feels' not right. So does anybody know the right way to reset whole state with new object? As far as I tested this.setState just changes the differences and leave other properties untouched.


Solution

  • You can't remove properties from the state, because it internally uses a merge

    nextState = Object.assign({}, nextState, partialState);
    

    So no way of removing already present keys. Only thing you can do is set the current keys to undefined. If you know the properties, you can set them manually.

    If not, you can try this to set them all to undefined:

    this.setState(
      Object.keys(this.state).reduce((a, c) => {
        a[c] = undefined;
        return a;
      }, {})
    )