0
votes
import React, { Component } from 'react';

import { createContext, useEffect, useReducer } from "react";

const INITIAL_STATE = { user: JSON.parse(localStorage.getItem("user")) || null, loading: false, error: null, };

export const AuthContext = createContext(INITIAL_STATE);

const AuthReducer = (state, action) => { switch (action.type) { case "LOGIN_START": return { user: null, loading: true, error: null, }; case "LOGIN_SUCCESS": return { user: action.payload, loading: false, error: null, }; case "LOGIN_FAILURE": return { user: null, loading: false, error: action.payload, }; case "LOGOUT": return { user: null, loading: false, error: null, }; default: return state; } };

export const AuthContextProvider = ({ children }) => { const [state, dispatch] = useReducer(AuthReducer, INITIAL_STATE);

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

return (
    <AuthContext.Provider
        value={{
            user: state.user,
            loading: state.loading,
            error: state.error,
            dispatch,
        }}
    >
        {children}
    </AuthContext.Provider>
);

};

1
Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. - Amit

1 Answers

0
votes

localStorage.getItem("user") is undefined. And because the || null is outside of the JSON.parse, it will try to parse undefined which will throw an error on the first character 'u'.

You should use: JSON.parse(localStorage.getItem("user") ?? null) and remove the outside || null