2023-08-14 13:48:38 +00:00
|
|
|
"use client";
|
|
|
|
|
2023-08-08 07:20:27 +00:00
|
|
|
import { createContext, useContext } from "react";
|
|
|
|
// mobx store
|
|
|
|
import { RootStore } from "store/root";
|
|
|
|
|
2023-08-14 13:48:38 +00:00
|
|
|
let rootStore: RootStore = new RootStore();
|
2023-08-08 07:20:27 +00:00
|
|
|
|
2023-08-14 13:48:38 +00:00
|
|
|
export const MobxStoreContext = createContext<RootStore>(rootStore);
|
2023-08-08 07:20:27 +00:00
|
|
|
|
|
|
|
const initializeStore = () => {
|
2023-08-14 13:48:38 +00:00
|
|
|
const _rootStore: RootStore = rootStore ?? new RootStore();
|
2023-08-08 07:20:27 +00:00
|
|
|
if (typeof window === "undefined") return _rootStore;
|
|
|
|
if (!rootStore) rootStore = _rootStore;
|
|
|
|
return _rootStore;
|
|
|
|
};
|
|
|
|
|
|
|
|
export const MobxStoreProvider = ({ children }: any) => {
|
2023-08-14 13:48:38 +00:00
|
|
|
const store: RootStore = initializeStore();
|
2023-08-08 07:20:27 +00:00
|
|
|
return <MobxStoreContext.Provider value={store}>{children}</MobxStoreContext.Provider>;
|
|
|
|
};
|
|
|
|
|
|
|
|
// hook
|
|
|
|
export const useMobxStore = () => {
|
|
|
|
const context = useContext(MobxStoreContext);
|
|
|
|
if (context === undefined) throw new Error("useMobxStore must be used within MobxStoreProvider");
|
|
|
|
return context;
|
|
|
|
};
|