Skip to content

Instantly share code, notes, and snippets.

@jamesplease
Created January 8, 2020 18:26
Show Gist options
  • Save jamesplease/ab7207cfd0f3aaf3ffd9990f8f4c8bed to your computer and use it in GitHub Desktop.
Save jamesplease/ab7207cfd0f3aaf3ffd9990f8f4c8bed to your computer and use it in GitHub Desktop.
Example code showing "plugins" / middleware for use-reducer-with-side-effects
import { composeReducers } from 'use-reducer-with-side-effects';
export default function createReducer(options = {}) {
const { plugins = [] } = options;
// Add built in plugins here if I want to
const allPlugins = plugins.concat([]);
const computedPlugins = allPlugins.map(plugin => {
const result = plugin(options);
return result;
});
return function defaultReducer(state, action) {
return composeReducers(computedPlugins)(state, action);
};
}
import { useMemo } from 'react';
import useCreateReducerWithEffect from 'use-reducer-with-side-effects';
import createReducer from './create-reducer';
import createLolomoChangePlugin from './lolomo-change-plugin/create-lolomo-change-plugin';
import newStateFromIndices from './lolomo-change-plugin/new-state-from-indices';
export default function useLolomoReducer(options = {}) {
// TODO: don't use useMemo...that can break!
const reducer = useMemo(
() => {
const plugins = Array.isArray(options.plugins) ? options.plugins : [];
const allPlugins = [createLolomoChangePlugin, ...plugins];
return createReducer({
...options,
plugins: allPlugins,
});
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[]
);
const [state, dispatch] = useCreateReducerWithEffect(
reducer,
{},
() => {
const { newState, newSideEffect } = newStateFromIndices({
// TODO: pull these from the options somehow
rowIndex: 0,
titleIndex: 0,
isInit: true,
...options,
});
// This is a workaround for
// https://github.com/conorhastings/use-reducer-with-side-effects/issues/9
return {
state: newState,
sideEffects: newSideEffect,
};
}
);
return [state, dispatch];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment