MCPcopy Create free account
hub / github.com/hashintel/hash / useDraftField

Function useDraftField

libs/@hashintel/petrinaut/src/ui/hooks/use-draft-field.ts:36–83  ·  view source on GitHub ↗
({
  sourceId,
  sourceValue,
}: {
  sourceId: string;
  sourceValue: T;
})

Source from the content-addressed store, hash-verified

34 * ```
35 */
36export const useDraftField = <T>({
37 sourceId,
38 sourceValue,
39}: {
40 sourceId: string;
41 sourceValue: T;
42}) => {
43 const [state, setState] = useState<DraftFieldState<T> | null>(null);
44
45 const isCurrent =
46 state?.sourceId === sourceId && Object.is(state.sourceValue, sourceValue);
47 const value = isCurrent ? state.value : sourceValue;
48 const error = isCurrent ? state.error : null;
49
50 const setValue = (nextValue: T) => {
51 setState((current) => {
52 const keepError =
53 current?.sourceId === sourceId &&
54 Object.is(current.sourceValue, sourceValue);
55
56 return {
57 sourceId,
58 sourceValue,
59 value: nextValue,
60 error: keepError ? current.error : null,
61 };
62 });
63 };
64
65 const setError = (nextError: string | null) => {
66 setState((current) => {
67 const currentValue =
68 current?.sourceId === sourceId &&
69 Object.is(current.sourceValue, sourceValue)
70 ? current.value
71 : sourceValue;
72
73 return {
74 sourceId,
75 sourceValue,
76 value: currentValue,
77 error: nextError,
78 };
79 });
80 };
81
82 return { value, setValue, error, setError };
83};

Callers 3

DraftFieldInputFunction · 0.90
PlaceMainContentFunction · 0.90

Calls 1

isMethod · 0.80

Tested by

no test coverage detected