0

I am using contextAPI for state management in react app. My Reducer.js has all the intialState stored.

Everytime I refresh the page initialState is set to default value and I loose my current state. Is there a way to restore entire initialState as it was before page refresh.

Below is the code for your reference.

Index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import { StateProvider } from './components/context-api/StateProvider';
import reducer, { initialState } from './components/context-api/Reducer';

ReactDOM.render(
  <React.StrictMode>
    <StateProvider initialState={initialState} reducer={reducer}>
      <App />
    </StateProvider>
  </React.StrictMode>,
  document.getElementById('root')
);

Reducer.js

export const initialState = {
    name: "",
    address: "",
    graduated: false,
    language: []
}

const reducer = (state, action) => {
    switch (action.type) {
        case "UPDATE_INFO":
            return {
                ...state,
                name: action.name,
                address: action.address,
                graduated: action.graduated,
                language: action.language,
            }
        default:
            return state;
    }
}
export default reducer;

StateProvider.js

import React, { createContext, useReducer, useContext } from "react";

export const StateContext = createContext();

export const StateProvider = ({ reducer, initialState, children }) => (
    <StateContext.Provider value={useReducer(reducer, initialState)}>
        {children}
    </StateContext.Provider>
)

export const useStateValue = () => useContext(StateContext);

App.js

import React from 'react'
import { useStateValue } from './components/context-api/StateProvider';


function App() {

    const [{ name, address, graduated, language }, dispatch] = useStateValue();

    const updateState = () => {

        dispatch({
            type: "UPDATE_INFO",
            name: "Test 1",
            address: "Chicago",
            graduated: true,
            language: ["Java", "JavaScript"]
        })
    }

    return (
        <div>
            <div>You Info</div>
            <p>name: {name}</p>
            <p>address:{address}</p>
            <p>graduated:{graduated}</p>
            <p>skills:{language}</p>
            <button onClick={updateState}></button>
        </div>
    )
}

export default App

I tried using localStorage and sessionStorgae and was able to store the value. But I was not able to restore the state in Reducers.js from session/localStorage.

How can I persist the initialState with value below on refresh.

            name: "Test 1",
            address: "Chicago",
            graduated: true,
            language: ["Java", "JavaScript"]
madhav koirala
  • 225
  • 3
  • 19

0 Answers0