Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reset initial state in React + ES6

I have a class, ElementBuilder below, and when the user saves the Element they've built, I want the state to reset to the values below.

I have some functions in this class that I haven't provided but that change the state of title, size, and color.

In ES 5, I would have a getInitialState function on my class and could call this.getInitialState() in a function.

This element lives in my app for the lifecycle of a logged in user and I want the default values to always be the same regardless of past usage.

How do I achieve this without writing a function that sets an object of default values (or maybe that's the answer)? thanks!

class ElementBuilder extends Component {
    constructor(props) {
        super(props);

        this.state = {
            title: 'Testing,
            size: 100,
            color: '#4d96ce',
        };
    }

    resetBuilder() {
        this.setState({ this.getInitialState() });
    }
}
like image 305
Zack Shapiro Avatar asked Jul 19 '17 20:07

Zack Shapiro


People also ask

How do you clear the state value in React?

Resetting States to Initial State Then we call useState in App to create the object state. Next, we create the clearState function to reset the state by calling the setState state setter function with a copy of the initialState . Making a copy lets React know that it has to update the state and re-render.

How do you initialize the state in React?

Initializing state In class components, there are two ways to initialize state — in a constructor function or as a Class property. Constructor functions, introduced in ES6, is the first function called in a class when it is first instantiated — meaning when a new object is created from the class.

Does re render reset state React?

No, The state will remain as it is until your component unmounts. If you want to trigger something while unmounting then you can use useEffect hook.


1 Answers

You may use a getter function:

class ElementBuilder extends Component {
  constructor(props) {
    super(props);

    this.state = this.initialState;
  }

  get initialState() {
    return {
      title: 'Testing',
      size: 100,
      color: '#4d96ce',
    };
  }

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

or just a variable:

constructor(props) {
  super(props);

  this.initialState = {
    title: 'Testing',
    size: 100,
    color: '#4d96ce',
  };
  this.state = this.initialState;
}
like image 138
quotesBro Avatar answered Oct 01 '22 13:10

quotesBro