-
Notifications
You must be signed in to change notification settings - Fork 0
/
app-store.ts
51 lines (42 loc) · 1.16 KB
/
app-store.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// file: src/app-store.ts
// Store for "app state" that needs to be accessible during client
// side operation and isolated during SSR
import { isServer, getRequestEvent } from 'solid-js/web';
import type { Context } from 'solid-js';
import type { HistoryAccess } from './types';
// 1. Add symbol key
const keyHistoryStore = Symbol('history-store');
// 2. Add value type
export type AppStore = {
[keyHistoryStore]: {
props:
| {
context: Context<HistoryAccess>;
incrementCount: () => void;
decrementCount: () => void;
historyAccess: HistoryAccess;
}
| undefined;
};
};
let appStore: AppStore | undefined;
// 3. Add initial value
export function makeAppStore(): AppStore {
return {
[keyHistoryStore]: {
props: undefined,
},
};
}
function getStore() {
if (isServer) {
const event = getRequestEvent();
if (!event) throw Error('RequestEvent not available yet');
const store = event.locals.appStore;
if (!store) throw Error('AppStore missing. Should be added by middleware');
return store;
}
return appStore ?? (appStore = makeAppStore());
}
// 4. Add selector
export const getHistoryStore = () => getStore()[keyHistoryStore];