-
Notifications
You must be signed in to change notification settings - Fork 0
/
create-server-context.tsx
36 lines (31 loc) · 1.21 KB
/
create-server-context.tsx
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
import type { ServerContext } from "./types";
import { AsyncLocalStorage } from "async_hooks";
import { serverGetterInClientComponentError } from "./server-getter-in-client-component-error";
import React from "react";
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const Enter = ({ storage, value }: { storage: AsyncLocalStorage<{ value: unknown }>; value: unknown }) => {
storage.enterWith({ value });
return <></>;
};
function createServerContext<T>(defaultValue?: T): ServerContext<T> {
serverGetterInClientComponentError("createServerContext");
const storage: ServerContext<T>["_storage"] = new AsyncLocalStorage<{ value: T }>();
return {
// The provider must always be asynchronous
Provider: async ({ children, value }) => {
return (
<>
<Enter storage={storage} value={value} />
{children}
</>
);
},
Consumer: ({ children }) => {
const store = storage.getStore();
return children(store ? store.value : defaultValue);
},
_storage: storage,
_defaultValue: defaultValue,
};
}
export default createServerContext;