[javascript] Clearing state es6 React

I am trying to clear a components state but can't find a reference for the es6 syntax. I was using:

this.replaceState(this.getInitialState());

however this does not work with the es6 class syntax.

How would I achieve the same result?

This question is related to javascript reactjs react-state

The answer is


In some circumstances, it's sufficient to just set all values of state to null.

If you're state is updated in such a way, that you don't know what might be in there, you might want to use

this.setState(Object.assign(...Object.keys(this.state).map(k => ({[k]: null}))))

Which will change the state as follows

{foo: 1, bar: 2, spam: "whatever"} > {foo: null, bar: null, spam: null}

Not a solution in all cases, but works well for me.


You can clone your state object, loop through each one, and set it to undefined. This method is not as good as the accepted answer, though.

const clonedState = this.state;

const keys = Object.keys(clonedState);
keys.forEach(key => (clonedState[key] = undefined));

this.setState(clonedState);

First, you'll need to store your initial state when using the componentWillMount() function from the component lifecycle:

componentWillMount() {
    this.initialState = this.state
}

This stores your initial state and can be used to reset the state whenever you need by calling

this.setState(this.initialState)

In most cases you dont need a deep copy, rarely initial state is object of objects, so using spread operator which babel transpiles to the object.assign should be fine.

So, inside constructor you would have:

    class MyComponent extends Component {
        constructor(props) {
            super(props)
            this.state = {
                key: value,
                key2: value
            }
            this.initialState = { ...this.state } 
        }
    }

From there you can use

this.setState(this.initialState);

to reset. But if for some reason your initial state is more complex object, use some library.


I will add to the above answer that the reset function should also assign state like so:

reset() {
  this.state = initialState;
  this.setState(initialState);
}

The reason being that if your state picks up a property that wasn't in the initial state, that key/value won't be cleared out, as setState just updates existing keys. Assignment is not enough to get the component to re-render, so include the setState call as well -- you could even get away with this.setState({}) after the assignment.


The solutions that involve setting this.state directly aren't working for me in React 16, so here is what I did to reset each key:

  const initialState = { example: 'example' }
  ...
  constructor() {
      super()
      this.state = initialState
  }
  ...
  reset() {
    const keys = Object.keys(this.state)
    const stateReset = keys.reduce((acc, v) => ({ ...acc, [v]: undefined }), {})
    this.setState({ ...stateReset, ...initialState })
  }

class MyComponent extends Component {
 constructor(props){
  super(props)
   this.state = {
     inputVal: props.inputValue
  }
   // preserve the initial state in a new object
   this.baseState = this.state 
}
  resetForm = () => {
    this.setState(this.baseState)
  }

}

use deep copy, you can do it with lodash:

import _ from "lodash";

const INITIAL_STATE = {};

constructor(props) {
    super(props);
    this.state = _.cloneDeep(INITIAL_STATE);
}

reset() {
    this.setState(_.cloneDeep(INITIAL_STATE));
}

const initialState = {
    a: '',
    b: '',
    c: ''
};

class ExampleComponent extends Component {
    state = { ...initialState } // use spread operator to avoid mutation
    handleReset = this.handleReset.bind(this);

    handleReset() {
         this.setState(initialState);
    }
 }

Remember that in order to be able to reset the state it is important not to mutate initialState.

state = {...initialState} // GOOD 
// => state points to a new obj in memory which has the values of initialState

state = initialState // BAD 
// => they point to the same obj in memory

The most convenient way would be to use ES6 Spread Operator. But you could also use Object.assign instead. They would both achieve the same.

state = Object.assign({}, initialState); // GOOD
state = {...initialState}; // GOOD

Problem

The accepted answer:

const initialState = {
    /* etc */
};

class MyComponent extends Component {
    constructor(props) {
        super(props)
        this.state = initialState;
    }
    reset() {
        this.setState(initialState);
    }
    /* etc */
}

unfortunately is not correct.

initialState is passed as a reference to this.state, so whenever you change state you also change initialState (const doesn't really matter here). The result is that you can never go back to initialState.

Solution

You have to deep copy initialState to state, then it will work. Either write a deep copy function yourself or use some existing module like this.


This is the solution implemented as a function:

Class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = this.getInitialState();
  }

  getInitialState = () => ({
    /* state props */
  })

  resetState = () => {
     this.setState(this.getInitialState());
  }
}

class x extends Components {
constructor() {
 super();
 this.state = {

  name: 'mark',
  age: 32,
  isAdmin: true,
  hits: 0,

  // since this.state is an object
  // simply add a method..

  resetSelectively() {
         //i don't want to reset both name and age
    // THIS IS FOR TRANSPARENCY. You don't need to code for name and age
    // it will assume the values in default..
    // this.name = this.name;   //which means the current state.
    // this.age = this.age;


    // do reset isAdmin and hits(suppose this.state.hits is 100 now)

    isAdmin = false;
    hits = 0;
  }// resetSelectively..

}//constructor..

/* now from any function i can just call */
myfunction() {
  /**
   * this function code..
   */
   resetValues();

}// myfunction..

resetValues() {
  this.state.resetSelectively();
}//resetValues

/////
//finally you can reset the values in constructor selectively at any point

...rest of the class..

}//class

This is how I handle it:

class MyComponent extends React.Component{
  constructor(props){
    super(props);
    this._initState = {
        a: 1,
        b: 2
      }
    this.state = this._initState;
  }

  _resetState(){
     this.setState(this._initState);
   }
}

Update: Actually this is wrong. For future readers please refer to @RaptoX answer. Also, you can use an Immutable library in order to prevent weird state modification caused by reference assignation.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to reactjs

Error: Node Sass version 5.0.0 is incompatible with ^4.0.0 TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined raised when starting react app Template not provided using create-react-app How to resolve the error on 'react-native start' Element implicitly has an 'any' type because expression of type 'string' can't be used to index Invalid hook call. Hooks can only be called inside of the body of a function component How to style components using makeStyles and still have lifecycle methods in Material UI? React Hook "useState" is called in function "app" which is neither a React function component or a custom React Hook function How to fix missing dependency warning when using useEffect React Hook? Unable to load script.Make sure you are either running a Metro server or that your bundle 'index.android.bundle' is packaged correctly for release

Examples related to react-state

What is useState() in React? React js change child component's state from parent component React - how to pass state to another component How do I access store state in React Redux? Understanding React-Redux and mapStateToProps() React - changing an uncontrolled input React with ES7: Uncaught TypeError: Cannot read property 'state' of undefined react change class name on state change Clearing state es6 React Updating state on props change in React Form