Skip to content Skip to sidebar Skip to footer

Reset Component State In React

I'm really struggling to reset the state back to it's orginal from with a method in React. My current reset method only resets the value. I have tried adding in const equal to the

Solution 1:

You could keep the initial state in a separate array, and create a copy of the array as initial state, and also create a copy of the array when using the handleReset.

Example

const counters = [
  { id: 1, value: 4 },
  { id: 2, value: 0 },
  { id: 3, value: 0 },
  { id: 4, value: 0 }
];

classAppextendsReact.Component {
  state = {
    counters: [...counters]
  };

  handleReset = () => {
    this.setState({ counters: [...counters] });
  };

  handleClick = index => {
    this.setState(prevState => {
      const counters = [...prevState.counters];

      counters[index] = {
        ...counters[index],
        value: counters[index].value + 1
      };

      return { counters };
    });
  };

  render() {
    return (
      <div>
        {this.state.counters.map((counter, index) => (
          <buttonid={counter.id}onClick={() => this.handleClick(index)}>
            {counter.value}
          </button>
        ))}
        <div><buttononClick={this.handleReset}>Reset</button></div></div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("root"));
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script><divid="root"></div>

Solution 2:

Not known to many, changing the key prop is one way to reset a component's state. When the key of an element changes, React will unmount it and reinstantiate the component.

If your component has a parent component and could get the parent component to change the key on your component. In the example below, the parent component has a key state that is a number. When you click the reset button, the parent component increases the key and the Counter component is remounted, thereby clearing all state. Any different value of key will cause the component to remount.

classCounterextendsReact.Component {
  state = {
    counters: [
      { id: 1, value: 4 },
      { id: 2, value: 0 },
      { id: 3, value: 0 },
      { id: 4, value: 0 }
    ],
  };
  
  handleClick = index => {
    this.setState(prevState => {
      const counters = [...prevState.counters];

      counters[index] = {
        ...counters[index],
        value: counters[index].value + 1
      };

      return { counters };
    });
  };

  render() {
    return (
      <div>
        {this.state.counters.map((counter, index) => (
          <buttonid={counter.id}onClick={() => this.handleClick(index)}>
            {counter.value}
          </button>
        ))}
        <div><buttononClick={this.props.handleReset}>Reset</button></div></div>
    );
  }
}

classAppextendsReact.Component {
  state = {
    key: 0,
  };

  handleReset = () => {
    this.setState(prevState => ({ 
      key: prevState.key + 1 
    }));
  };

  render() {
    return (
      <div><Counterkey={this.state.key}handleReset={this.handleReset}
        /></div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("root"));
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script><scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script><divid="root"></div>

Solution 3:

With the assumption that your state is valid JSON, this seems a simple solution:

const initialState = {...};

class ... {
    this.state = JSON.parse(JSON.stringify(initialState));

    reset = () => {
        this.setState(JSON.parse(JSON.stringify(initialState)));
    }
}

Deep cloning, no libs needed, native code.

Post a Comment for "Reset Component State In React"