Created
September 16, 2022 16:05
-
-
Save julrich/e7ec6c4a2a417ba4afcd654e45db5fc6 to your computer and use it in GitHub Desktop.
Immer.js based state provider in React
This file contains hidden or 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
import { | |
createContext, | |
FC, | |
PropsWithChildren, | |
useContext, | |
useEffect, | |
} from "react"; | |
import noop from "lodash/noop"; | |
import { Updater, useImmer, History } from "../utils/useImmer"; | |
import { Journey } from "../types/journey"; | |
import { useLoad } from "../services/useLoadJourney"; | |
export const JourneyContext = createContext< | |
[Journey | undefined, Updater<Journey | undefined>, Omit<History, "clear">] | |
>([, noop, {}]); | |
export const JourneyContextProvider: FC<PropsWithChildren> = (props) => { | |
const [journey, setJourney, { undo, redo, clear: clearHistory }] = useImmer< | |
Journey | undefined | |
>(undefined); | |
const { data } = useLoad(); | |
useEffect(() => { | |
if (data) { | |
setJourney(() => data); | |
clearHistory(); | |
window.__enc_journey = data; // for preview | |
} | |
// eslint-disable-next-line react-hooks/exhaustive-deps | |
}, [data]); | |
return ( | |
<JourneyContext.Provider | |
{...props} | |
value={[journey, setJourney, { undo, redo }]} | |
/> | |
); | |
}; | |
export const useJourney = () => useContext(JourneyContext); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment