Search code examples
javascriptreactjsreact-nativestatereset

Reset component state in React Native


I want to reset the state of only certain (not all) states. On the click of a button, values of present_count, total_count, present and total should be set to their initial state (0). While the state of subjects and text should remain intact.

constructor(props) {
    super(props);
    this.state = { 
      subjects: [],
      text: "",
      present_count: [0, 0, 0, 0, 0, 0, 0],
      total_count: [0, 0, 0, 0, 0, 0, 0],
      present: 0,
      total: 0
    }
}

EDIT: I am using AsyncStorage to save the modified state.


Solution

  • You can use spread operator to override the current state values and then use the current state value of text, subjects:

    // default state 
    const defaultState = {
      subjects: [],
      text: "",
      present_count: [0, 0, 0, 0, 0, 0, 0],
      total_count: [0, 0, 0, 0, 0, 0, 0],
      present: 0,
      total: 0
    }
    
    // component constructor.
    constructor(props) {
        super(props);
        this.state = { ...defaultState };
    }
    
    // click event handler    
    handleClick = () => {
      this.setState({
        ...defaultState,
        subjects: this.state.subjects,
        text: this.state.text
      });
    }