-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcell.tsx
40 lines (33 loc) · 892 Bytes
/
cell.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
37
38
39
40
import { useEffect, useState } from "react";
import type { AnyCell } from "@okcontract/cells";
type UseCellReturnType<T> = T | undefined;
export function useCell<T>(
cell: AnyCell<T> | null | undefined,
): UseCellReturnType<T>;
export function useCell<T>(
cell: AnyCell<T> | null | undefined,
defaultValue: T,
): T;
export function useCell<T>(
cell: AnyCell<T> | null | undefined,
defaultValue?: T,
): UseCellReturnType<T> {
const [value, setValue] = useState<T | undefined>(defaultValue);
useEffect(() => {
if (cell === null || cell === undefined) {
setValue(defaultValue);
return;
}
const unsubscribe = cell.subscribe((newValue: T | Error) => {
if (newValue instanceof Error) {
console.error(newValue);
return;
}
setValue(newValue);
});
return () => {
unsubscribe();
};
}, [cell, defaultValue]);
return value as UseCellReturnType<T>;
}