Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import React, { useEffect, useReducer, createContext } from 'react';
- import axios from "axios";
- import { Reducer } from "./reducer";
- import { config } from "../../config/config";
- import { SET_LOADING, LOAD_USER, AUTH_ERROR, LOGIN_SUCCESS, LOGIN_FAIL, CLEAR_ERRORS } from "../../store/actions/types";
- const { AUTH_URL, httpHeaders, setAuthHeaderToken } = config;
- const initialState = {
- loading: false,
- sreToken: localStorage.getItem('sreToken'),
- isAuthenticated: false,
- user: null,
- error: null
- };
- export const AuthContext = createContext(initialState);
- export const AuthState = ({ children }) => {
- const [state, dispatch] = useReducer(Reducer, initialState);
- const setLoading = () => dispatch({ type: SET_LOADING });
- // load user: hits the auth endpoint to check the token (if available) and return the user info
- const loadUser = async () => {
- if(localStorage.sre) {
- setAuthHeaderToken(localStorage.sre);
- }
- try {
- const { data } = await axios.get(AUTH_URL.loadUser);
- console.log(data);
- return dispatch({ type: LOAD_USER, payload: data.user });
- } catch (e) {
- console.log(e);
- dispatch({ type: AUTH_ERROR, payload: e });
- localStorage.removeItem('sre');
- }
- };
- // login: logs in the user and sets up the token
- const login = async userCredentials => {
- try {
- console.log(userCredentials);
- setLoading();
- const { data } = await axios.post(AUTH_URL.login, userCredentials, httpHeaders);
- await dispatch({ type: LOGIN_SUCCESS, payload: data.token });
- await loadUser();
- } catch (e) {
- console.log(e);
- localStorage.removeItem('sre');
- dispatch({ type: LOGIN_FAIL, payload: `Invalid credentials, ${e}` });
- }
- };
- const clearErrors = () => dispatch({ type: CLEAR_ERRORS });
- return (
- <AuthContext.Provider value={{
- loading: state.loading,
- isAuthenticated: state.isAuthenticated,
- user: state.user,
- error: state.error,
- setLoading,
- loadUser,
- login,
- clearErrors
- }}>
- { children }
- </AuthContext.Provider>
- )
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement