Search code examples
javascriptreactjsfrontendstatereact-state-management

My ReactJS initialState change when my state changes


I have something like:

const initialState={
 hide: true
 product:[
         {name: ''
          price: ''},
          {name: ''
          price: ''},
          {name: ''
          price: ''},
         ]
}

class Products extends Component {
  state = { ...initialState }

}
clearState = () =>{
  this.setState({...initialState})
}

I want to clear the state by using the initialState object, but when i try to do it nothing happens. I noticed that my initialState is taking the same values as my state, so, when i execute other functions to edit the state, my initialState change too.

Any advice? Thanks by the way


Solution

  • Your initial state is still storing a reference to the array, which means if you change the array anywhere else it will change everywhere.

    To combat this problem, you could use a function that would create a new initialState for you to use, like this:

    const initialState = () => {
        return {
            hide: true,
            product: [
                {name: '', price: ''},
                {name: '', price: ''},
                {name: '', price: ''},
            ]
        };
    };
    
    class Products extends Component {
        state = initialState();
    
        clearState = () =>{
            this.setState(initialState());
        }
    }