Skip to content

Instantly share code, notes, and snippets.

@julrich
Created September 16, 2022 16:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save julrich/e7ec6c4a2a417ba4afcd654e45db5fc6 to your computer and use it in GitHub Desktop.
Save julrich/e7ec6c4a2a417ba4afcd654e45db5fc6 to your computer and use it in GitHub Desktop.
Immer.js based state provider in React
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