UNPKG

react-auth-verification-context

Version:

react-auth-verification-context is a library that provides a way to manage authentication state in a React application. It is implemented using the React context API, which allows you to pass data through the component tree without having to pass props do

47 lines (46 loc) 1.71 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.useAuth = exports.AuthProvider = void 0; const jsx_runtime_1 = require("react/jsx-runtime"); const react_1 = require("react"); const auth_reducer_1 = require("../reducers/auth.reducer"); const AuthStateContext = (0, react_1.createContext)({ isLoading: false, attributes: null, isAuthenticated: false, login: () => { return null; }, logout: () => { return null; }, restoreToken: () => { return null; }, }); const AuthProvider = (0, react_1.memo)(({ children }) => { const [state, dispatch] = (0, react_1.useReducer)(auth_reducer_1.authReducer, { isLoading: true, attributes: null, isAuthenticated: false, }); const login = (0, react_1.useCallback)((user) => { dispatch({ type: auth_reducer_1.AuthActions.SignIn, payload: user }); }, []); const logout = (0, react_1.useCallback)(() => { dispatch({ type: auth_reducer_1.AuthActions.SignOut, payload: null }); }, []); const restoreToken = (0, react_1.useCallback)((user) => { dispatch({ type: auth_reducer_1.AuthActions.RestoreToken, payload: user }); }, []); return ((0, jsx_runtime_1.jsx)(AuthStateContext.Provider, Object.assign({ value: Object.assign(Object.assign({}, state), { login, logout, restoreToken }) }, { children: children }))); }); exports.AuthProvider = AuthProvider; function useAuth() { const context = (0, react_1.useContext)(AuthStateContext); if (context === undefined) { throw new Error('useAuthState must be used within a AuthProvider'); } return context; } exports.useAuth = useAuth;