Skip to content

Instantly share code, notes, and snippets.

@malte-wessel
Last active December 8, 2018 23:46
Show Gist options
  • Save malte-wessel/92deee1fbf797ff3ec528dc24b5dbb21 to your computer and use it in GitHub Desktop.
Save malte-wessel/92deee1fbf797ff3ec528dc24b5dbb21 to your computer and use it in GitHub Desktop.
const EPIC_END = Symbol('EPIC_END');
const createEpicStore = (reducer, initialState, epic) => {
let epicMiddleware = createEpicMiddleware();
let store = createStore(
reducer,
initialState,
applyMiddleware(epicMiddleware)
);
const run = () => {
const rootEpic = (action, ...rest) =>
epic(action, ...rest).pipe(
takeUntil(action.ofType({ type: EPIC_END }))
);
epicMiddleware.current.run(rootEpic);
return () => {
store.dispatch({ type: EPIC_END });
store = undefined;
epicMiddleware = undefined;
};
};
return {
...store,
run
};
};
const useEpic = (reducer, initialState, epic) => {
const store = useRef();
const [state, setState] = useState(initialState);
if (!store.current) {
store.current = createEpicStore(reducer, initialState, epic);
}
useEffectOnce(() => {
const unsubscribe = store.current.subscribe(() =>
setState(store.current.getState())
);
const destroy = store.run();
return () => {
unsubscribe();
destroy();
};
});
return [state, store.dispatch];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment