Last active
February 9, 2021 16:07
-
-
Save knjname/5ad277f684464419d171dd58026df6cc to your computer and use it in GitHub Desktop.
A react hook for mobx-state-tree that preserves the last state when reloading
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
import { getSnapshot, Instance } from "mobx-state-tree"; | |
import { createContext, useEffect, useState } from "react"; | |
import { MyStore } from "./MyStore"; | |
export const useMyStore = () => { | |
const [state, setState] = useState(() => MyStore.create()); | |
useEffect(() => { | |
if ((window as any).reentrant) { | |
const newState = MyStore.create(getSnapshot(state)); | |
setState(newState); | |
} | |
return () => { | |
(window as any).reentrant = true; | |
}; | |
}, []); | |
return state; | |
}; | |
export const MyStoreContext = createContext<Instance<typeof MyStore>>( | |
undefined as any | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment