1

I am using react hooks and context api . I get a user info. when i log in, which was null by default in the context. But when i refresh the page the value does not persist in the context api . How can i save the user info. ?

import AuthReducer from "./AuthReducer";
const INITIAL_STATE = {
  user: null,

  isFetching: false,
  error: false,
};

export const AuthContext = createContext(INITIAL_STATE);

export const AuthContextProvider = ({ children }) => {
  const [state, dispatch] = useReducer(AuthReducer, INITIAL_STATE);
  return (
    <AuthContext.Provider
      value={{
        user: state.user,
        isFetching: state.isFetching,
        error: state.error,
        dispatch,
      }}
    >
      {children}
    </AuthContext.Provider>
  );
};
Relex Mode
  • 19
  • 2
  • 4
  • 1
    Persist it to localStorage upon state change. Use an initializer function when the context mounts to read from localStorage and initialize your reducer state. If you need more help from here I can provide guidance. – Drew Reese Jul 24 '21 at 06:37
  • Did you initialize state from localStorage? That's part of the solution of persisting app state for page reloads. – Drew Reese Jul 24 '21 at 07:13
  • 1
    i solve this like this useEffect(() => { if (state.user!==null) { localStorage.setItem("currentuser", JSON.stringify(state.user)); } }, [state]) ; so now i can use currentuser – Relex Mode Jul 24 '21 at 07:17
  • i don't know how to initialize state from localStorage – Relex Mode Jul 24 '21 at 07:24
  • That is covered in the linked answer in the "Round out the rest of the app" section. – Drew Reese Jul 24 '21 at 07:26

0 Answers0