import React, { createContext, useReducer, useContext } from "react"; function authReducer(state, action) { switch (action.type) { case "INITIATE_LOGIN": return { ...state, isLoading: true }; case "CANCEL_LOGIN": return { ...state, isLoading: false }; case "SET_ACCESS_TOKEN": return { ...state, accessToken: action.payload, isStarting: false, isLoading: false }; case "SET_ID_TOKEN": return { ...state, idToken: action.payload }; case "SET_REFRESH_TOKEN": return { ...state, refreshToken: action.payload }; case "LOGOUT": return { ...state, isLoggedIn: false, idToken: null, refreshToken: null}; default: throw new Error(); } } const AuthContext = createContext(); const state = { accessToken: null, idToken: null, refreshToken: null, isLoading: false, isStarting: true, isLogout: false, }; export const AuthProvider = ({ children }) => { const [authState, authDispatch] = useReducer(authReducer, state); return ( {children} ); }; export const useAuthState = () => { const context = useContext(AuthContext); if (context === undefined) { throw new Error( "useAuthState must be used within a AuthProvider" ); } return context; }