Skip to content

Instantly share code, notes, and snippets.

@xnimorz
Last active November 1, 2019 14:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xnimorz/352a6c8cca7b9967ffc3bee2e50edaf0 to your computer and use it in GitHub Desktop.
Save xnimorz/352a6c8cca7b9967ffc3bee2e50edaf0 to your computer and use it in GitHub Desktop.
Batched actions and reducer concept
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