2020-04-08 09:44:28 +02:00
|
|
|
import { useMemo } from "react";
|
2019-05-29 13:57:26 +02:00
|
|
|
import {
|
|
|
|
applySnapshot,
|
|
|
|
Instance,
|
|
|
|
SnapshotIn,
|
|
|
|
SnapshotOut,
|
|
|
|
types,
|
|
|
|
} from "mobx-state-tree";
|
2018-09-04 17:17:30 +02:00
|
|
|
|
2020-04-08 09:44:28 +02:00
|
|
|
let store: IStore | undefined;
|
2018-09-04 17:17:30 +02:00
|
|
|
|
|
|
|
const Store = types
|
|
|
|
.model({
|
|
|
|
lastUpdate: types.Date,
|
|
|
|
light: false,
|
|
|
|
})
|
2020-05-18 21:24:37 +02:00
|
|
|
.actions((self) => {
|
2020-04-08 09:44:28 +02:00
|
|
|
let timer: any;
|
2018-09-04 17:17:30 +02:00
|
|
|
const start = () => {
|
|
|
|
timer = setInterval(() => {
|
2018-10-14 10:04:58 +02:00
|
|
|
// mobx-state-tree doesn't allow anonymous callbacks changing data.
|
|
|
|
// Pass off to another action instead (need to cast self as any
|
2021-11-08 18:24:53 +01:00
|
|
|
// because TypeScript doesn't yet know about the actions we're
|
2018-09-04 17:17:30 +02:00
|
|
|
// adding to self here)
|
2019-05-29 13:57:26 +02:00
|
|
|
(self as any).update();
|
|
|
|
}, 1000);
|
|
|
|
};
|
2018-09-04 17:17:30 +02:00
|
|
|
const update = () => {
|
2019-05-29 13:57:26 +02:00
|
|
|
self.lastUpdate = new Date(Date.now());
|
|
|
|
self.light = true;
|
|
|
|
};
|
2018-09-04 17:17:30 +02:00
|
|
|
const stop = () => {
|
2019-05-29 13:57:26 +02:00
|
|
|
clearInterval(timer);
|
|
|
|
};
|
|
|
|
return { start, stop, update };
|
|
|
|
});
|
2018-09-04 17:17:30 +02:00
|
|
|
|
2019-05-29 13:57:26 +02:00
|
|
|
export type IStore = Instance<typeof Store>;
|
|
|
|
export type IStoreSnapshotIn = SnapshotIn<typeof Store>;
|
|
|
|
export type IStoreSnapshotOut = SnapshotOut<typeof Store>;
|
2018-09-04 17:17:30 +02:00
|
|
|
|
2020-04-08 09:44:28 +02:00
|
|
|
export function initializeStore(snapshot = null) {
|
|
|
|
const _store = store ?? Store.create({ lastUpdate: 0 });
|
|
|
|
|
|
|
|
// If your page has Next.js data fetching methods that use a Mobx store, it will
|
|
|
|
// get hydrated here, check `pages/ssg.tsx` and `pages/ssr.tsx` for more details
|
2018-09-04 17:17:30 +02:00
|
|
|
if (snapshot) {
|
2020-04-08 09:44:28 +02:00
|
|
|
applySnapshot(_store, snapshot);
|
2018-09-04 17:17:30 +02:00
|
|
|
}
|
2020-04-08 09:44:28 +02:00
|
|
|
// For SSG and SSR always create a new store
|
|
|
|
if (typeof window === "undefined") return _store;
|
|
|
|
// Create the store once in the client
|
|
|
|
if (!store) store = _store;
|
|
|
|
|
|
|
|
return store;
|
|
|
|
}
|
|
|
|
|
|
|
|
export function useStore(initialState: any) {
|
|
|
|
const store = useMemo(() => initializeStore(initialState), [initialState]);
|
2019-05-29 13:57:26 +02:00
|
|
|
return store;
|
|
|
|
}
|