Last active
December 8, 2018 23:46
-
-
Save malte-wessel/92deee1fbf797ff3ec528dc24b5dbb21 to your computer and use it in GitHub Desktop.
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
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