Created
July 25, 2016 06:32
-
-
Save zivni/677638f712b9d16f78ee1903b5a11596 to your computer and use it in GitHub Desktop.
Redux reducer enhancer to store specific control instance state by key
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
/** | |
* Use this reducer enhancer to store specific control instance state by key. | |
* The key will be resolved using the controlInstanceKeyResolver function parmeter which defaults to use the controlInstanceKey member of the action's meta object (i.e action.meta.controlInstanceKey) | |
* If the key is not a string then the action will be ignored and will not pass to the enhanched reducer. | |
* @param {function} reducer - the reducer to enhance | |
* @param {function} controlInstanceKeyResolver - an optional function to get the instance key from the action | |
*/ | |
export function instanceMapReducerEnhancer( | |
reducer: Redux.Reducer, | |
controlInstanceKeyResolver: ((action) => string) = defaultKeyResolver) { | |
return function (state = {}, action) { | |
const instanceKey = controlInstanceKeyResolver(action); | |
if (typeof (instanceKey) === "string") { | |
let instanceState = reducer(state[instanceKey], action); | |
const newState = Object.assign({}, state, { [instanceKey]: instanceState }); | |
return newState | |
} else { | |
return state; | |
} | |
} | |
} | |
function defaultKeyResolver(action) { | |
return action.meta ? action.meta.controlInstanceKey : undefined; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Use this reducer enhancer, when you have the same UI control with multiple instances whose state you need to keep around in Redux state,
Give each instance a unique key and pass this key in the actions.
this way your reducer needs to only handle just the state of one instance of the control actions. The enhancer will take care of mapping the the specific state into a object map using the key provided in the action.