Search code examples
reactjstypescriptlocal-storagereact-context

iam trying to save the main array into the local storage but the value is not getting stored in react context api


here i have tried to save the main array inside the localstorge and retrive the storage to use as global state but the data is not getting stored inside the local storage

this file is my context

import  { createContext, useReducer, ReactNode, FC, useCallback, useEffect } from "react";
import { AppReducer } from "./AppReducer";
import { Log } from "../components/LoggingPage";


export interface maintask {
    taskName:string;
    id:number;
    logs:Log[]
}
interface firstSate {
    mainlogs:[]
}

export interface InitialState {
       mainlogs:maintask [];
}

export interface addlog{
        id:number;
        log:Log;
    }
export interface updatelog{
    mainId:number;
    updatedLog:Log;
}
export interface deleteLog{
    mainLogId:number;
    logId:number
}
 interface loggings{
    id:number;
    log:Log
 }


export interface GlobalContextTypes {
        state: InitialState;
        addMainLogs: (mainTask: maintask) => void;
        deleteMainLogs:(id:number) =>void;
        addLogs:(addLog:loggings) =>void;
        updateLogs:(updatelog:updatelog) => void;
        deleteLogs:(deleteLog:deleteLog)=>void;
}

const state:InitialState = {
    mainlogs:[]
}
const storedState = localStorage.getItem('state');
const initialState: InitialState = storedState ? JSON.parse(storedState) : state
export const GlobalContext = createContext<GlobalContextTypes | null>(null);

const GlobalProvider: FC<{ children: ReactNode }> = ({ children }): JSX.Element => {
    const [state, dispatch] = useReducer(AppReducer, initialState);
  
    useEffect(() =>{
        localStorage.setItem('state',JSON.stringify(initialState))

    },[initialState])
     
     

    const addMainLogs= (newlog:maintask ) => {
        dispatch({
            type: 'ADD_MAIN_LOG',
            payload: newlog
        });

    };

    const deleteMainLogs = (id:number) =>{
        dispatch({
            type:'DELETE_MAIN_LOG',
            payload:id
        })
    }

    const addLogs = (addLog:addlog) =>{
        dispatch({
            type:'ADD_LOGS',
            payload:addLog,
        })

    }

    const updateLogs = (updatedLog:updatelog) => {
        dispatch({
            type:'UPDATE_LOGS',
            payload:updatedLog
        })
    }

    const deleteLogs = (deleteLog:deleteLog) => {
        dispatch({
            type:'DELETE_LOGS',
            payload:deleteLog
        })
         
    }

    const contextValue: GlobalContextTypes = {
        state,
        addMainLogs,
        deleteMainLogs,
        addLogs,
        updateLogs,
        deleteLogs,
    };

    return (
        <GlobalContext.Provider value={contextValue}>
            {children}
        </GlobalContext.Provider>
    );
}

export default GlobalProvider;

i have set the state to localstorage usign useffect but still the data is not saving inside the local storage


Solution

  • I can see that in the dependency array there is initialState variable and for setting local storage item "state" again initialState is given. The variable (which is actually constant) initialState never changes, since it is produced from getting item "state", which at the first is always null (the local storage initially is empty). Since it never changes, it actually do not trigger the useEffect.

    The correct code have to be:

     useEffect(() => {
        localStorage.setItem('state',JSON.stringify(state))
     },[state])
    

    Whenever the "state" changes, it will trigger useEffect and you will have the actual state in the local storage. In the next load - you will have correct value too.