rsnext/examples/with-mobx-state-tree/store.ts
Steven 4466ba436b
chore(examples): use default prettier for examples/templates (#60530)
## Description
This PR ensures that the default prettier config is used for examples
and templates.

This config is compatible with `prettier@3` as well (upgrading prettier
is bigger change that can be a future PR).

## Changes
- Updated `.prettierrc.json` in root with `"trailingComma": "es5"` (will
be needed upgrading to prettier@3)
- Added `examples/.prettierrc.json` with default config (this will
change every example)
- Added `packages/create-next-app/templates/.prettierrc.json` with
default config (this will change every template)

## Related

- Fixes #54402
- Closes #54409
2024-01-11 16:01:44 -07:00

61 lines
1.7 KiB
TypeScript

import { useMemo } from "react";
import {
applySnapshot,
Instance,
SnapshotIn,
SnapshotOut,
types,
} from "mobx-state-tree";
let store: IStore | undefined;
const Store = types
.model({
lastUpdate: types.Date,
light: false,
})
.actions((self) => {
let timer: any;
const start = () => {
timer = setInterval(() => {
// mobx-state-tree doesn't allow anonymous callbacks changing data.
// Pass off to another action instead (need to cast self as any
// because TypeScript doesn't yet know about the actions we're
// adding to self here)
(self as any).update();
}, 1000);
};
const update = () => {
self.lastUpdate = new Date(Date.now());
self.light = true;
};
const stop = () => {
clearInterval(timer);
};
return { start, stop, update };
});
export type IStore = Instance<typeof Store>;
export type IStoreSnapshotIn = SnapshotIn<typeof Store>;
export type IStoreSnapshotOut = SnapshotOut<typeof Store>;
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
if (snapshot) {
applySnapshot(_store, snapshot);
}
// 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]);
return store;
}