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
|
2024-03-19 14:38:35 +00:00
|
|
|
import { RootStore } from "@/store/root";
|
2023-08-08 07:20:27 +00:00
|
|
|
|
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 = () => {
|
2024-03-06 13:09:14 +00:00
|
|
|
const singletonRootStore: RootStore = rootStore ?? new RootStore();
|
|
|
|
if (typeof window === "undefined") return singletonRootStore;
|
|
|
|
if (!rootStore) rootStore = singletonRootStore;
|
|
|
|
return singletonRootStore;
|
2023-08-08 07:20:27 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
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;
|
|
|
|
};
|