forked from rocicorp/mono
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuse-zero.tsx
More file actions
32 lines (28 loc) · 1.08 KB
/
use-zero.tsx
File metadata and controls
32 lines (28 loc) · 1.08 KB
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
import {createContext, useContext} from 'react';
import type {Zero} from '../../zero-client/src/client/zero.ts';
import type {Schema} from '../../zero-schema/src/builder/schema-builder.ts';
import type {CustomMutatorDefs} from '../../zero-client/src/client/custom.ts';
// eslint-disable-next-line @typescript-eslint/naming-convention
const ZeroContext = createContext<unknown | undefined>(undefined);
export function useZero<
S extends Schema,
MD extends CustomMutatorDefs<S> | undefined = undefined,
>(): Zero<S, MD> {
const zero = useContext(ZeroContext);
if (zero === undefined) {
throw new Error('useZero must be used within a ZeroProvider');
}
return zero as Zero<S, MD>;
}
export function createUseZero<
S extends Schema,
MD extends CustomMutatorDefs<S> | undefined = undefined,
>() {
return () => useZero<S, MD>();
}
export function ZeroProvider<
S extends Schema,
MD extends CustomMutatorDefs<S> | undefined = undefined,
>({children, zero}: {children: React.ReactNode; zero: Zero<S, MD>}) {
return <ZeroContext.Provider value={zero}>{children}</ZeroContext.Provider>;
}