( host: SettingsHost | undefined, id: string, )
| 3 | import type { SettingsHost, SettingValue } from '../types/settings'; |
| 4 | |
| 5 | export 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 | }; |
no test coverage detected