Skip to content

Instantly share code, notes, and snippets.

@arosenb2
Last active February 13, 2019 15:15
Show Gist options
  • Save arosenb2/b14da3bdf08ce206e204743a74803bca to your computer and use it in GitHub Desktop.
Save arosenb2/b14da3bdf08ce206e204743a74803bca to your computer and use it in GitHub Desktop.
O(1) Reducer
const actionTypes = {
USER_LOGIN_SUBMIT: 'USER_LOGIN_SUBMIT',
USER_LOGIN_SUCCESS: 'USER_LOGIN_SUCCESS',
USER_LOGIN_FAILURE: 'USER_LOGIN_FAILURE'
};
const createInitialState = (initialState = {}) => ({
id: null,
email: null,
isLoading: false,
error: undefined,
...initialState,
});
const reducerMap = {
[actionTypes.USER_LOGIN_SUBMIT]: (state) => ({
...state,
isLoading: true
}),
[actionTypes.USER_LOGIN_SUCCESS]: (state, action) => ({
...state,
id: action.payload.id,
email: action.payload.email,
isLoading: false,
error: undefined
}),
[actionTypes.USER_LOGIN_FAILURE]: (state, action) => ({
...state,
isLoading: false,
error: action.payload
})
};
const userReducer = (state = loadInitialState(), action) => {
const reducer = reducerMap[action.type];
return reducer ? reducer(state, action) : state;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment