MCPcopy Index your code
hub / github.com/nukeop/nuclear / useSetting

Function useSetting

packages/plugin-sdk/src/react/useSetting.ts:5–51  ·  view source on GitHub ↗
(
  host: SettingsHost | undefined,
  id: string,
)

Source from the content-addressed store, hash-verified

3import type { SettingsHost, SettingValue } from '../types/settings';
4
5export const useSetting = <T extends SettingValue = SettingValue>(
6 host: SettingsHost | undefined,
7 id: string,
8) => {
9 const [currentValue, setCurrentValue] = useState<T | undefined>(undefined);
10
11 useEffect(() => {
12 if (!host) {
13 return;
14 }
15 let isMounted = true;
16 let hasReceivedUpdate = false;
17 const unsubscribe = host.subscribe<T>(id, (nextValue) => {
18 if (!isMounted) {
19 return;
20 }
21 hasReceivedUpdate = true;
22 setCurrentValue(nextValue);
23 });
24 host.get<T>(id).then((initialValue) => {
25 if (!isMounted) {
26 return;
27 }
28 if (!hasReceivedUpdate) {
29 setCurrentValue(initialValue);
30 }
31 });
32 return () => {
33 isMounted = false;
34 if (unsubscribe) {
35 unsubscribe();
36 }
37 };
38 }, [id, host]);
39
40 const setValue = useMemo(
41 () => (nextValue: T) => {
42 if (!host) {
43 return;
44 }
45 void host.set<T>(id, nextValue);
46 },
47 [id, host],
48 );
49
50 return [currentValue, setValue] as const;
51};

Callers 2

SettingFieldWithHostFunction · 0.90
useCoreSettingFunction · 0.90

Calls 2

subscribeMethod · 0.45
getMethod · 0.45

Tested by

no test coverage detected