Created
January 9, 2018 22:37
-
-
Save trevorblades/54702e6f92a08bbf3d1c6274a29147b8 to your computer and use it in GitHub Desktop.
Different options for async or object-based reducers
This file contains 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 user = 'foo'; | |
// option 1: actions first | |
const defaultState = { | |
loading: false, | |
error: null, | |
properties: user | |
}; | |
const option1 = handleActions( | |
{ | |
[loading]: state => ({ | |
...state, | |
loading: true | |
}), | |
[success]: (state, {payload: token}) => ({ | |
...state, | |
loading: false, | |
error: null, | |
properties: userFromToken(token) | |
}), | |
[failure]: (state, {payload: error}) => ({ | |
...state, | |
loading: false, | |
error | |
}), | |
[logOut]: () => ({ | |
...defaultState, | |
properties: null | |
}) | |
}, | |
defaultState | |
); | |
// option 2: properties first | |
const option2 = combineReducers({ | |
loading: handleActions( | |
{ | |
[loading]: () => true, | |
[combineActions(success, failure)]: () => false | |
}, | |
false | |
), | |
error: handleActions( | |
{ | |
[failure]: (state, {payload: error}) => error, | |
[success]: () => null | |
}, | |
null | |
), | |
properties: handleActions( | |
{ | |
[success]: (state, {payload: token}) => userFromToken(token), | |
[logOut]: () => null | |
}, | |
user | |
) | |
}); | |
// option 3: option 1 + option 2 🙀 | |
const reducer = handleActions( | |
{ | |
[setProperty]: (state, {payload}) => ({ | |
...state, | |
[payload.key]: payload.value | |
}), | |
[setProperties]: (state, {payload}) => ({ | |
...state, | |
...payload | |
}) | |
}, | |
{ | |
changed: null | |
} | |
); | |
const option3 = combineReducers({ | |
...reducer, | |
changed: handleAction( | |
combineActions(setProperty, setProperties), | |
() => Date.now(), | |
null | |
) | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment