|
1 | | -import {useMemo} from "react"; |
2 | 1 | import {type BannerWidgetConfig, readWidgetConfig} from "../BannerConfig.ts"; |
3 | 2 | import {activity} from "../activity"; |
| 3 | +import {useEffect, useState} from "react"; |
4 | 4 |
|
5 | 5 | export function useWidgetConfig( |
6 | 6 | host: HTMLElement |
7 | | -): BannerWidgetConfig | null { |
8 | | - return useMemo(() => { |
9 | | - const baseConfig = readWidgetConfig(host); |
10 | | - if (!baseConfig) { |
11 | | - activity('bootstrap', 'Widget is not correctly configured', null, 'error'); |
12 | | - return null; |
| 7 | +): { |
| 8 | + config: BannerWidgetConfig | null; |
| 9 | + error: Error | null; |
| 10 | + loading: boolean; |
| 11 | +} { |
| 12 | + |
| 13 | + const [config, setConfig] = useState<BannerWidgetConfig | null>(null); |
| 14 | + const [error, setError] = useState<Error | null>(null); |
| 15 | + const [loading, setLoading] = useState(true); |
| 16 | + |
| 17 | + useEffect(() => { |
| 18 | + let cancelled = false; |
| 19 | + |
| 20 | + async function bootstrap() { |
| 21 | + try { |
| 22 | + setLoading(true); |
| 23 | + const resolved = await readWidgetConfig(host); |
| 24 | + |
| 25 | + if (!cancelled) { |
| 26 | + setConfig(resolved); |
| 27 | + setError(null); |
| 28 | + } |
| 29 | + } catch (err) { |
| 30 | + activity('bootstrap', 'Config error', { |
| 31 | + error: (err as Error).message |
| 32 | + }); |
| 33 | + |
| 34 | + if (!cancelled) { |
| 35 | + setError(err as Error); |
| 36 | + setConfig(null); |
| 37 | + } |
| 38 | + } finally { |
| 39 | + if (!cancelled) setLoading(false); |
| 40 | + } |
13 | 41 | } |
14 | 42 |
|
15 | | - activity('bootstrap', 'Widget config', baseConfig); |
| 43 | + bootstrap(); |
| 44 | + |
| 45 | + return () => { |
| 46 | + cancelled = true; |
| 47 | + }; |
16 | 48 |
|
17 | | - return baseConfig |
18 | 49 | }, [host]); |
19 | | -} |
20 | 50 |
|
| 51 | + return { config, error, loading }; |
| 52 | +} |
21 | 53 |
|
22 | 54 |
|
0 commit comments