AuthContext.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import React, { createContext, useReducer, useContext } from "react";
  2. function authReducer(state, action) {
  3. switch (action.type) {
  4. case "INITIATE_LOGIN":
  5. return { ...state, isLoading: true };
  6. case "CANCEL_LOGIN":
  7. return { ...state, isLoading: false };
  8. case "SET_ACCESS_TOKEN":
  9. return { ...state, accessToken: action.payload, isStarting: false, isLoading: false };
  10. case "SET_ID_TOKEN":
  11. return { ...state, idToken: action.payload };
  12. case "SET_REFRESH_TOKEN":
  13. return { ...state, refreshToken: action.payload };
  14. case "LOGOUT":
  15. return { ...state, isLoggedIn: false, idToken: null, refreshToken: null};
  16. default:
  17. throw new Error();
  18. }
  19. }
  20. const AuthContext = createContext();
  21. const state = {
  22. accessToken: null,
  23. idToken: null,
  24. refreshToken: null,
  25. isLoading: false,
  26. isStarting: true,
  27. isLogout: false,
  28. };
  29. export const AuthProvider = ({ children }) => {
  30. const [authState, authDispatch] = useReducer(authReducer, state);
  31. return (
  32. <AuthContext.Provider value={{ authState, authDispatch }}>
  33. {children}
  34. </AuthContext.Provider>
  35. );
  36. };
  37. export const useAuthState = () => {
  38. const context = useContext(AuthContext);
  39. if (context === undefined) {
  40. throw new Error(
  41. "useAuthState must be used within a AuthProvider"
  42. );
  43. }
  44. return context;
  45. }