Last active
November 1, 2019 14:07
-
-
Save xnimorz/352a6c8cca7b9967ffc3bee2e50edaf0 to your computer and use it in GitHub Desktop.
Batched actions and reducer concept
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
export const BATCH = 'BATCHING_ACTIONS'; | |
// actions — массив экшенов, вида [ | |
// {type: "actionType1", payload: {}, ...}, | |
// {type: "actionType2", payload: {}, ...}, | |
// ... | |
//] | |
// Функция формирует из custom action классический redux экшен, иначе, когда экшен дойдет до стора redux выдаст ошибку | |
export const batchActionCreator = (actions) => ({ | |
type: BATCH, | |
payload: actions, | |
}); | |
// новый корневой редьюсер (оборачиваем обычный привычный нам редьюсер в него. | |
// то есть вызываем стор вот так: | |
// createStore(batchReducer({reducerA, reducerB, ...})); | |
export const batchReducer = (rootReducer) => { | |
return (state, action) => { | |
if (action.type === BATCH) { | |
return action.payload.reduce((state, action) => { | |
return rootReducer(state, action); | |
}, state); | |
} | |
return rootReducer(state, action); | |
}; | |
}; | |
// Подключаем кастомный middleware, который будет преобразовывать экшены | |
// [action1, action2] в {type: BATCH, payload: [action1, action2]} | |
export default ({ dispatch }) => (next) => (action) => { | |
if (Array.isArray(action)) { | |
if (action.find((action) => action instanceof Function)) { | |
Debug.log('out error', 'Thunks in batched actions are forbidden', action); | |
} | |
return dispatch(batchActionCreator(action)); | |
} | |
return next(action); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment