Search code examples
reactjsreact-hooksstoreuse-contextuse-reducer

React: How to make store invulnerable for reload?


I created store with useReducer, and provide state and dispatch function by Context provider:

/*code...*/
import { InsuranceItemContext } from './Context/InsuranceItemContext';
import { reducer } from './Reducer/Reducer';

function App() {
  const [state, dispatch] = React.useReducer(reducer, undefined);
  return (
    <BrowserRouter>
      <InsuranceItemContext.Provider value={{state, dispatch}}>
        <div className='App'>
          <Header />
          <Section />
          <Footer />
        </div>
      </InsuranceItemContext.Provider>
    </BrowserRouter>
  );
}

export default App;

In the next file, I receive data and transfer it to the store by dispatch function:

/*some code...*/
<input onClick={() => dispatch({
        type: 'ADD_ITEM',
        payload: {
            coverage: coverageValue,
            risk: props.risk,
            price,
            title: props.title
        }
    })} type='submit' name='submit' className='submit' />
/*some code...*/

Each component of my app works correctly but I have one trouble: my store's data vanish each time I reload a page or render another component.
How can I fix it?


Solution

  • For that purpose, I should use localStorage. Because It saves data on the user device (browser).
    So, If I want to record some data to localStorage I have to use these instructions:

     localStorage.setItem() //for recording
     localStorage.getItem() //for reading
    

    My main mistake was recording data without JSON.stringify() function, because localStorage transform my data into string (in my case it was an object and the result was [object Object]).

    All in all, I got it, and changed my code to the variant:

     localStorage.setItem('variable', JSON.stringify(variable)) //for recording
     JSON.parse(localStorage.getItem('variable')) //for reading
    

    JSON.parse() I use for decrypting json notation and receive data in original view.
    So, here my changes:

    /*some code*/ 
    function App() {
      const [state, dispatch] = useReducer(reducer, null);
      useEffect(() => {
        if (state) localStorage.setItem('state', JSON.stringify(state));
      }, [state]);
      useEffect(() => {
        dispatch({type:'GET_DATA', payload: 
            JSON.parse(localStorage.getItem('state'))});
      }, []);
      console.log('Local storage: ' + JSON.stringify(window.localStorage.state));
      console.log('My storage: ' + JSON.stringify(state));
    }
    /*some code*/