Last active
February 13, 2019 15:15
-
-
Save arosenb2/b14da3bdf08ce206e204743a74803bca to your computer and use it in GitHub Desktop.
O(1) Reducer
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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