Skip to content

Instantly share code, notes, and snippets.

@klosowsk
Last active May 20, 2019 18:14
Show Gist options
  • Save klosowsk/6b3fbe1120d7929d487cbbd2ba8862f9 to your computer and use it in GitHub Desktop.
Save klosowsk/6b3fbe1120d7929d487cbbd2ba8862f9 to your computer and use it in GitHub Desktop.
Login Reducer, Context and Provider
import React, { createContext, useReducer } from 'react';
import * as types from 'constants/actionTypes';
const LoginContext = createContext();
const initialState = {
isLoggedIn: false,
token: null,
loading: false,
error: null,
};
const reducer = (state, action) => {
switch (action.type) {
case types.LOGIN:
return {
...state,
isLoggedIn: true,
token: action.payload.token,
error: null,
loading: false,
};
case types.LOGOUT:
return {
...state,
isLoggedIn: false,
token: null,
error: null,
loading: false,
};
case types.LOGIN_ERROR:
return {
...state,
isLoggedIn: false,
token: null,
error: action.payload.error,
loading: false,
};
case types.LOGIN_LOADING:
return {
...state,
isLoggedIn: false,
token: null,
error: null,
loading: true,
};
default:
console.log('WARNING -> Unknown reducer type.');
return {
...state,
};
}
};
const actions = dispatch => {
return {
login: token =>
dispatch({
type: types.LOGIN,
payload: {
token,
},
}),
logout: () =>
dispatch({
type: types.LOGOUT,
}),
loginError: error =>
dispatch({
type: types.LOGIN_ERROR,
payload: {
error,
},
}),
loginLoading: () =>
dispatch({
type: types.LOGIN_LOADING,
}),
};
};
const LoginContextProvider = props => {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<LoginContext.Provider
value={{ ...state, dispatch, actions: actions(dispatch) }}
>
{props.children}
</LoginContext.Provider>
);
};
export { LoginContext, LoginContextProvider };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment