@module-federation/bridge-react 0.0.0-next-20250630125121 → 0.0.0-next-20250701070959

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/CHANGELOG.md +10 -6
  2. package/__tests__/bridge.spec.tsx +7 -7
  3. package/dist/{bridge-base-UGCwcMnG.js → bridge-base-BBH982Tz.cjs} +1 -1
  4. package/dist/{bridge-base-BoshEggF.mjs → bridge-base-P6pEjY1q.js} +1 -1
  5. package/dist/index-Cv3p6r66.cjs +235 -0
  6. package/dist/index-D4yt7Udv.js +236 -0
  7. package/dist/index.cjs.js +9 -434
  8. package/dist/index.d.ts +0 -142
  9. package/dist/index.es.js +11 -437
  10. package/dist/router-v5.cjs.js +1 -1
  11. package/dist/router-v5.es.js +1 -1
  12. package/dist/router-v6.cjs.js +1 -1
  13. package/dist/router-v6.es.js +1 -1
  14. package/dist/router.cjs.js +1 -1
  15. package/dist/router.es.js +1 -1
  16. package/dist/v18.cjs.js +1 -1
  17. package/dist/v18.es.js +1 -1
  18. package/dist/v19.cjs.js +1 -1
  19. package/dist/v19.es.js +1 -1
  20. package/package.json +5 -45
  21. package/src/index.ts +1 -30
  22. package/src/remote/component.tsx +3 -3
  23. package/src/remote/create.tsx +4 -17
  24. package/tsconfig.json +1 -1
  25. package/vite.config.ts +0 -13
  26. package/dist/data-fetch-runtime-plugin.cjs.js +0 -73
  27. package/dist/data-fetch-runtime-plugin.d.ts +0 -6
  28. package/dist/data-fetch-runtime-plugin.es.js +0 -74
  29. package/dist/data-fetch-server-middleware.cjs.js +0 -163
  30. package/dist/data-fetch-server-middleware.d.ts +0 -6
  31. package/dist/data-fetch-server-middleware.es.js +0 -164
  32. package/dist/data-fetch-utils.cjs.js +0 -1271
  33. package/dist/data-fetch-utils.d.ts +0 -77
  34. package/dist/data-fetch-utils.es.js +0 -1273
  35. package/dist/index-C0fDZB5b.js +0 -45
  36. package/dist/index-CqxytsLY.mjs +0 -46
  37. package/dist/index.esm-BCeUd-x9.mjs +0 -418
  38. package/dist/index.esm-j_1sIRzg.js +0 -417
  39. package/dist/inject-data-fetch-CAvi-gSf.js +0 -79
  40. package/dist/inject-data-fetch-errCdqBS.mjs +0 -80
  41. package/dist/lazy-utils.cjs.js +0 -24
  42. package/dist/lazy-utils.d.ts +0 -140
  43. package/dist/lazy-utils.es.js +0 -24
  44. package/dist/utils-Bk8hGjjF.mjs +0 -2016
  45. package/dist/utils-iEVlDmyk.js +0 -2015
  46. package/src/lazy/AwaitDataFetch.tsx +0 -176
  47. package/src/lazy/constant.ts +0 -30
  48. package/src/lazy/createLazyComponent.tsx +0 -393
  49. package/src/lazy/data-fetch/cache.ts +0 -296
  50. package/src/lazy/data-fetch/call-data-fetch.ts +0 -13
  51. package/src/lazy/data-fetch/data-fetch-server-middleware.ts +0 -196
  52. package/src/lazy/data-fetch/index.ts +0 -15
  53. package/src/lazy/data-fetch/inject-data-fetch.ts +0 -109
  54. package/src/lazy/data-fetch/prefetch.ts +0 -102
  55. package/src/lazy/data-fetch/runtime-plugin.ts +0 -116
  56. package/src/lazy/index.ts +0 -31
  57. package/src/lazy/logger.ts +0 -6
  58. package/src/lazy/types.ts +0 -75
  59. package/src/lazy/utils.ts +0 -372
  60. package/src/lazy/wrapNoSSR.tsx +0 -10
@@ -1,176 +0,0 @@
1
- import React, { MutableRefObject, ReactNode, Suspense, useRef } from 'react';
2
- import logger from './logger';
3
- import {
4
- DATA_FETCH_ERROR_PREFIX,
5
- LOAD_REMOTE_ERROR_PREFIX,
6
- ERROR_TYPE,
7
- DATA_FETCH_FUNCTION,
8
- } from './constant';
9
-
10
- import { getDataFetchIdWithErrorMsgs, wrapDataFetchId } from './utils';
11
- import type { DataFetchParams } from './types';
12
-
13
- function isPromise<T>(obj: any): obj is PromiseLike<T> {
14
- return (
15
- !!obj &&
16
- (typeof obj === 'object' || typeof obj === 'function') &&
17
- typeof obj.then === 'function'
18
- );
19
- }
20
- const AWAIT_ERROR_PREFIX =
21
- '<Await /> caught the following error during render: ';
22
-
23
- export type ErrorInfo = {
24
- error: Error;
25
- errorType: number;
26
- dataFetchMapKey?: string;
27
- };
28
-
29
- export const transformError = (err: string | Error): ErrorInfo => {
30
- const errMsg = err instanceof Error ? err.message : err;
31
- const originalMsg = errMsg.replace(AWAIT_ERROR_PREFIX, '');
32
- const dataFetchMapKey = getDataFetchIdWithErrorMsgs(originalMsg);
33
- if (originalMsg.indexOf(DATA_FETCH_ERROR_PREFIX) === 0) {
34
- return {
35
- error: new Error(
36
- originalMsg
37
- .replace(DATA_FETCH_ERROR_PREFIX, '')
38
- .replace(wrapDataFetchId(dataFetchMapKey), ''),
39
- ),
40
- errorType: ERROR_TYPE.DATA_FETCH,
41
- dataFetchMapKey,
42
- };
43
- }
44
- if (originalMsg.indexOf(LOAD_REMOTE_ERROR_PREFIX) === 0) {
45
- return {
46
- error: new Error(
47
- originalMsg
48
- .replace(LOAD_REMOTE_ERROR_PREFIX, '')
49
- .replace(wrapDataFetchId(dataFetchMapKey), ''),
50
- ),
51
- errorType: ERROR_TYPE.LOAD_REMOTE,
52
- dataFetchMapKey,
53
- };
54
- }
55
-
56
- return {
57
- error: new Error(originalMsg.replace(wrapDataFetchId(dataFetchMapKey), '')),
58
- errorType: ERROR_TYPE.UNKNOWN,
59
- dataFetchMapKey,
60
- };
61
- };
62
-
63
- export interface AwaitProps<T> {
64
- resolve: T | Promise<T>;
65
- loading?: ReactNode;
66
- errorElement?: ReactNode | ((errorInfo: ErrorInfo) => ReactNode);
67
- children: (data: T) => ReactNode;
68
- params?: DataFetchParams;
69
- }
70
-
71
- export interface AwaitErrorHandlerProps<T = any>
72
- extends Omit<AwaitProps<T>, 'resolve'> {
73
- resolve: () => T | string;
74
- }
75
-
76
- const DefaultLoading = <></>;
77
- const DefaultErrorElement = (_data: any) => <div>Error</div>;
78
-
79
- export function AwaitDataFetch<T>({
80
- resolve,
81
- loading = DefaultLoading,
82
- errorElement = DefaultErrorElement,
83
- children,
84
- params,
85
- }: AwaitProps<T>) {
86
- const dataRef = useRef<T>();
87
- const data = dataRef.current || resolve;
88
- const getData = isPromise(data) ? fetchData(data, dataRef) : () => data;
89
-
90
- return (
91
- <AwaitSuspense
92
- params={params}
93
- loading={loading}
94
- errorElement={errorElement}
95
- // @ts-ignore
96
- resolve={getData}
97
- >
98
- {children}
99
- </AwaitSuspense>
100
- );
101
- }
102
-
103
- function AwaitSuspense<T>({
104
- resolve,
105
- children,
106
- loading = DefaultLoading,
107
- errorElement = DefaultErrorElement,
108
- }: AwaitErrorHandlerProps<T>) {
109
- return (
110
- <Suspense fallback={loading}>
111
- <ResolveAwait resolve={resolve} errorElement={errorElement}>
112
- {children}
113
- </ResolveAwait>
114
- </Suspense>
115
- );
116
- }
117
-
118
- function ResolveAwait<T>({
119
- children,
120
- resolve,
121
- errorElement,
122
- params,
123
- }: AwaitErrorHandlerProps<T>) {
124
- const data = resolve();
125
- logger.debug('resolve data: ', data);
126
- if (typeof data === 'string' && data.indexOf(AWAIT_ERROR_PREFIX) === 0) {
127
- const transformedError = transformError(data);
128
- return (
129
- <>
130
- {typeof errorElement === 'function' ? (
131
- <>
132
- {globalThis.FEDERATION_SSR && (
133
- <script
134
- suppressHydrationWarning
135
- dangerouslySetInnerHTML={{
136
- __html: String.raw`
137
- globalThis['${DATA_FETCH_FUNCTION}'] = globalThis['${DATA_FETCH_FUNCTION}'] || []
138
- globalThis['${DATA_FETCH_FUNCTION}'].push([${transformedError.dataFetchMapKey ? `'${transformedError.dataFetchMapKey}'` : ''},${params ? JSON.stringify(params) : null},true]);`,
139
- }}
140
- ></script>
141
- )}
142
- {errorElement(transformedError)}
143
- </>
144
- ) : (
145
- errorElement
146
- )}
147
- </>
148
- );
149
- }
150
- const toRender =
151
- typeof children === 'function' ? children(data as T) : children;
152
- return <>{toRender}</>;
153
- }
154
-
155
- // return string when promise is rejected
156
- const fetchData = <T,>(promise: Promise<T>, ref: MutableRefObject<T>) => {
157
- let data: T | string;
158
- let status: 'pending' | 'success' = 'pending';
159
- const suspender = promise
160
- .then((res) => {
161
- status = 'success';
162
- data = res;
163
- ref.current = res;
164
- })
165
- .catch((e) => {
166
- status = 'success';
167
- console.warn(e);
168
- data = AWAIT_ERROR_PREFIX + e;
169
- });
170
- return () => {
171
- if (status === 'pending') {
172
- throw suspender;
173
- }
174
- return data;
175
- };
176
- };
@@ -1,30 +0,0 @@
1
- export const PLUGIN_IDENTIFIER = '[ Module Federation React ]';
2
- export const DOWNGRADE_KEY = '_mfSSRDowngrade';
3
- export const DATA_FETCH_MAP_KEY = '__MF_DATA_FETCH_MAP__';
4
- export const DATA_FETCH_FUNCTION = '_mfDataFetch';
5
- export const FS_HREF = '_mfFSHref';
6
- export const ERROR_TYPE = {
7
- DATA_FETCH: 1,
8
- LOAD_REMOTE: 2,
9
- UNKNOWN: 3,
10
- };
11
- export const WRAP_DATA_FETCH_ID_IDENTIFIER = 'wrap_dfip_identifier';
12
- export const enum MF_DATA_FETCH_TYPE {
13
- FETCH_SERVER = 1,
14
- FETCH_CLIENT = 2,
15
- }
16
-
17
- export const enum MF_DATA_FETCH_STATUS {
18
- LOADED = 1,
19
- LOADING = 2,
20
- AWAIT = 0,
21
- ERROR = 3,
22
- }
23
-
24
- export const DATA_FETCH_IDENTIFIER = 'data';
25
- export const DATA_FETCH_CLIENT_SUFFIX = '.client';
26
- export const DATA_FETCH_QUERY = 'x-mf-data-fetch';
27
- export const DATA_FETCH_ERROR_PREFIX =
28
- 'caught the following error during dataFetch: ';
29
- export const LOAD_REMOTE_ERROR_PREFIX =
30
- 'caught the following error during loadRemote: ';
@@ -1,393 +0,0 @@
1
- import React, { ReactNode, useState, useEffect } from 'react';
2
- import logger from './logger';
3
- import { AwaitDataFetch, transformError } from './AwaitDataFetch';
4
- import {
5
- fetchData,
6
- getDataFetchItem,
7
- getDataFetchMapKey,
8
- getDataFetchInfo,
9
- getLoadedRemoteInfos,
10
- setDataFetchItemLoadedStatus,
11
- wrapDataFetchId,
12
- } from './utils';
13
- import {
14
- DATA_FETCH_ERROR_PREFIX,
15
- DATA_FETCH_FUNCTION,
16
- FS_HREF,
17
- LOAD_REMOTE_ERROR_PREFIX,
18
- MF_DATA_FETCH_TYPE,
19
- } from './constant';
20
-
21
- import type { ErrorInfo } from './AwaitDataFetch';
22
- import type { DataFetchParams, NoSSRRemoteInfo } from './types';
23
- import type { FederationHost, getInstance } from '@module-federation/runtime';
24
-
25
- export type IProps = {
26
- id: string;
27
- instance: ReturnType<typeof getInstance>;
28
- injectScript?: boolean;
29
- injectLink?: boolean;
30
- };
31
-
32
- export type CreateLazyComponentOptions<T, E extends keyof T> = {
33
- loader: () => Promise<T>;
34
- instance: ReturnType<typeof getInstance>;
35
- loading: React.ReactNode;
36
- fallback: ReactNode | ((errorInfo: ErrorInfo) => ReactNode);
37
- export?: E;
38
- dataFetchParams?: DataFetchParams;
39
- noSSR?: boolean;
40
- cacheData?: boolean;
41
- };
42
-
43
- type ReactKey = { key?: React.Key | null };
44
-
45
- function getTargetModuleInfo(id: string, instance?: FederationHost) {
46
- if (!instance) {
47
- return;
48
- }
49
- const loadedRemoteInfo = getLoadedRemoteInfos(id, instance);
50
- if (!loadedRemoteInfo) {
51
- return;
52
- }
53
- const snapshot = loadedRemoteInfo.snapshot;
54
- if (!snapshot) {
55
- return;
56
- }
57
- const publicPath =
58
- 'publicPath' in snapshot
59
- ? snapshot.publicPath
60
- : 'getPublicPath' in snapshot
61
- ? new Function(snapshot.getPublicPath)()
62
- : '';
63
- if (!publicPath) {
64
- return;
65
- }
66
- const modules = 'modules' in snapshot ? snapshot.modules : [];
67
- const targetModule = modules.find(
68
- (m) => m.modulePath === loadedRemoteInfo.expose,
69
- );
70
- if (!targetModule) {
71
- return;
72
- }
73
-
74
- const remoteEntry = 'remoteEntry' in snapshot ? snapshot.remoteEntry : '';
75
- if (!remoteEntry) {
76
- return;
77
- }
78
- return {
79
- module: targetModule,
80
- publicPath,
81
- remoteEntry,
82
- };
83
- }
84
-
85
- export function collectSSRAssets(options: IProps) {
86
- const {
87
- id,
88
- injectLink = true,
89
- injectScript = false,
90
- } = typeof options === 'string' ? { id: options } : options;
91
- const links: React.ReactNode[] = [];
92
- const scripts: React.ReactNode[] = [];
93
- const instance = options.instance;
94
- if (!instance || (!injectLink && !injectScript)) {
95
- return [...scripts, ...links];
96
- }
97
-
98
- const moduleAndPublicPath = getTargetModuleInfo(id, instance);
99
- if (!moduleAndPublicPath) {
100
- return [...scripts, ...links];
101
- }
102
- const { module: targetModule, publicPath, remoteEntry } = moduleAndPublicPath;
103
- if (injectLink) {
104
- [...targetModule.assets.css.sync, ...targetModule.assets.css.async]
105
- .sort()
106
- .forEach((file, index) => {
107
- links.push(
108
- <link
109
- key={`${file.split('.')[0]}_${index}`}
110
- href={`${publicPath}${file}`}
111
- rel="stylesheet"
112
- type="text/css"
113
- />,
114
- );
115
- });
116
- }
117
-
118
- if (injectScript) {
119
- scripts.push(
120
- <script
121
- async={true}
122
- key={remoteEntry.split('.')[0]}
123
- src={`${publicPath}${remoteEntry}`}
124
- crossOrigin="anonymous"
125
- />,
126
- );
127
- [...targetModule.assets.js.sync].sort().forEach((file, index) => {
128
- scripts.push(
129
- <script
130
- key={`${file.split('.')[0]}_${index}`}
131
- async={true}
132
- src={`${publicPath}${file}`}
133
- crossOrigin="anonymous"
134
- />,
135
- );
136
- });
137
- }
138
-
139
- return [...scripts, ...links];
140
- }
141
-
142
- function getServerNeedRemoteInfo(
143
- loadedRemoteInfo: ReturnType<typeof getLoadedRemoteInfos>,
144
- id: string,
145
- noSSR?: boolean,
146
- ): NoSSRRemoteInfo | undefined {
147
- if (
148
- noSSR ||
149
- (typeof window !== 'undefined' && window.location.href !== window[FS_HREF])
150
- ) {
151
- if (!loadedRemoteInfo?.version) {
152
- throw new Error(`${loadedRemoteInfo?.name} version is empty`);
153
- }
154
- const { snapshot } = loadedRemoteInfo;
155
- if (!snapshot) {
156
- throw new Error(`${loadedRemoteInfo?.name} snapshot is empty`);
157
- }
158
- const dataFetchItem = getDataFetchItem(id);
159
- const isFetchServer =
160
- dataFetchItem?.[0]?.[1] === MF_DATA_FETCH_TYPE.FETCH_SERVER;
161
-
162
- if (
163
- isFetchServer &&
164
- (!('ssrPublicPath' in snapshot) || !snapshot.ssrPublicPath)
165
- ) {
166
- throw new Error(
167
- `ssrPublicPath is required while fetching ${loadedRemoteInfo?.name} data in SSR project!`,
168
- );
169
- }
170
-
171
- if (
172
- isFetchServer &&
173
- (!('ssrRemoteEntry' in snapshot) || !snapshot.ssrRemoteEntry)
174
- ) {
175
- throw new Error(
176
- `ssrRemoteEntry is required while loading ${loadedRemoteInfo?.name} data loader in SSR project!`,
177
- );
178
- }
179
-
180
- return {
181
- name: loadedRemoteInfo.name,
182
- version: loadedRemoteInfo.version,
183
- ssrPublicPath:
184
- 'ssrPublicPath' in snapshot ? snapshot.ssrPublicPath || '' : '',
185
- ssrRemoteEntry:
186
- 'ssrRemoteEntry' in snapshot ? snapshot.ssrRemoteEntry || '' : '',
187
- globalName: loadedRemoteInfo.entryGlobalName,
188
- };
189
- }
190
- return undefined;
191
- }
192
-
193
- export function createLazyComponent<T, E extends keyof T>(
194
- options: CreateLazyComponentOptions<T, E>,
195
- ) {
196
- const { instance, cacheData } = options;
197
- if (!instance) {
198
- throw new Error('instance is required for createLazyComponent!');
199
- }
200
- let dataCache: unknown = null;
201
-
202
- type ComponentType = T[E] extends (...args: any) => any
203
- ? Parameters<T[E]>[0] extends undefined
204
- ? ReactKey
205
- : Parameters<T[E]>[0] & ReactKey
206
- : ReactKey;
207
- const exportName = options?.export || 'default';
208
-
209
- const callLoader = async () => {
210
- logger.debug('callLoader start', Date.now());
211
- const m = (await options.loader()) as Record<string, React.FC> &
212
- Record<symbol, string>;
213
- logger.debug('callLoader end', Date.now());
214
- if (!m) {
215
- throw new Error('load remote failed');
216
- }
217
- return m;
218
- };
219
-
220
- const getData = async (noSSR?: boolean) => {
221
- let loadedRemoteInfo: ReturnType<typeof getLoadedRemoteInfos>;
222
- let moduleId: string;
223
- try {
224
- const m = await callLoader();
225
- moduleId = m && m[Symbol.for('mf_module_id')];
226
- if (!moduleId) {
227
- throw new Error('moduleId is empty');
228
- }
229
- loadedRemoteInfo = getLoadedRemoteInfos(moduleId, instance);
230
- if (!loadedRemoteInfo) {
231
- throw new Error(`can not find loaded remote('${moduleId}') info!`);
232
- }
233
- } catch (e) {
234
- const errMsg = `${LOAD_REMOTE_ERROR_PREFIX}${e}`;
235
- logger.debug(e);
236
- throw new Error(errMsg);
237
- }
238
- let dataFetchMapKey: string | undefined;
239
- try {
240
- dataFetchMapKey = getDataFetchMapKey(
241
- getDataFetchInfo({
242
- name: loadedRemoteInfo.name,
243
- alias: loadedRemoteInfo.alias,
244
- id: moduleId,
245
- remoteSnapshot: loadedRemoteInfo.snapshot,
246
- }),
247
- { name: instance.name, version: instance.options.version },
248
- );
249
- logger.debug('getData dataFetchMapKey: ', dataFetchMapKey);
250
- if (!dataFetchMapKey) {
251
- return;
252
- }
253
- const data = await fetchData(
254
- dataFetchMapKey,
255
- {
256
- ...options.dataFetchParams,
257
- isDowngrade: false,
258
- },
259
- getServerNeedRemoteInfo(loadedRemoteInfo, dataFetchMapKey, noSSR),
260
- );
261
- setDataFetchItemLoadedStatus(dataFetchMapKey);
262
- logger.debug('get data res: \n', data);
263
- dataCache = data;
264
- return data;
265
- } catch (err) {
266
- const errMsg = `${DATA_FETCH_ERROR_PREFIX}${wrapDataFetchId(dataFetchMapKey)}${err}`;
267
- logger.debug(errMsg);
268
- throw new Error(errMsg);
269
- }
270
- };
271
-
272
- const LazyComponent = React.lazy(async () => {
273
- const m = await callLoader();
274
- const moduleId = m && m[Symbol.for('mf_module_id')];
275
- const loadedRemoteInfo = getLoadedRemoteInfos(moduleId, instance);
276
- loadedRemoteInfo?.snapshot;
277
- const dataFetchMapKey = loadedRemoteInfo
278
- ? getDataFetchMapKey(
279
- getDataFetchInfo({
280
- name: loadedRemoteInfo.name,
281
- alias: loadedRemoteInfo.alias,
282
- id: moduleId,
283
- remoteSnapshot: loadedRemoteInfo.snapshot,
284
- }),
285
- { name: instance.name, version: instance?.options.version },
286
- )
287
- : undefined;
288
- logger.debug('LazyComponent dataFetchMapKey: ', dataFetchMapKey);
289
-
290
- const assets = collectSSRAssets({
291
- id: moduleId,
292
- instance,
293
- });
294
-
295
- const Com = m[exportName] as React.FC<ComponentType>;
296
- if (exportName in m && typeof Com === 'function') {
297
- return {
298
- default: (props: Omit<ComponentType, 'key'> & { mfData?: unknown }) => (
299
- <>
300
- {globalThis.FEDERATION_SSR && dataFetchMapKey && (
301
- <script
302
- suppressHydrationWarning
303
- dangerouslySetInnerHTML={{
304
- __html: String.raw`
305
- globalThis['${DATA_FETCH_FUNCTION}'] = globalThis['${DATA_FETCH_FUNCTION}'] || [];
306
- globalThis['${DATA_FETCH_FUNCTION}'].push(['${dataFetchMapKey}',${JSON.stringify(props.mfData)}]);
307
- `,
308
- }}
309
- ></script>
310
- )}
311
- {globalThis.FEDERATION_SSR && assets}
312
- <Com {...props} />
313
- </>
314
- ),
315
- };
316
- } else {
317
- throw Error(
318
- `Make sure that ${moduleId} has the correct export when export is ${String(
319
- exportName,
320
- )}`,
321
- );
322
- // eslint-disable-next-line max-lines
323
- }
324
- });
325
-
326
- return (props: ComponentType) => {
327
- const { key, ...args } = props;
328
- if (cacheData && dataCache) {
329
- // @ts-expect-error ignore
330
- return <LazyComponent {...args} mfData={dataCache} />;
331
- }
332
- if (!options.noSSR) {
333
- return (
334
- <AwaitDataFetch
335
- resolve={getData(options.noSSR)}
336
- loading={options.loading}
337
- errorElement={options.fallback}
338
- >
339
- {/* @ts-expect-error ignore */}
340
- {(data) => <LazyComponent {...args} mfData={data} />}
341
- </AwaitDataFetch>
342
- );
343
- } else {
344
- // Client-side rendering logic
345
- const [data, setData] = useState<unknown>(null);
346
- const [loading, setLoading] = useState<boolean>(true);
347
- const [error, setError] = useState<ErrorInfo | null>(null);
348
-
349
- useEffect(() => {
350
- let isMounted = true;
351
- const fetchDataAsync = async () => {
352
- try {
353
- setLoading(true);
354
- const result = await getData(options.noSSR);
355
- if (isMounted) {
356
- setData(result);
357
- }
358
- } catch (e) {
359
- if (isMounted) {
360
- setError(transformError(e as Error));
361
- }
362
- } finally {
363
- if (isMounted) {
364
- setLoading(false);
365
- }
366
- }
367
- };
368
-
369
- fetchDataAsync();
370
-
371
- return () => {
372
- isMounted = false;
373
- };
374
- }, []);
375
-
376
- if (loading) {
377
- return <>{options.loading}</>;
378
- }
379
-
380
- if (error) {
381
- return (
382
- <>
383
- {typeof options.fallback === 'function'
384
- ? options.fallback(error)
385
- : options.fallback}
386
- </>
387
- );
388
- }
389
- // @ts-expect-error ignore
390
- return <LazyComponent {...args} mfData={data} />;
391
- }
392
- };
393
- }