-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathuseManifest.ts
More file actions
49 lines (39 loc) · 1.35 KB
/
useManifest.ts
File metadata and controls
49 lines (39 loc) · 1.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import { useEffect, useState } from 'react';
import { appendChunck } from '../../modules/container/utils';
import { TManifest } from '../../types';
interface IUseManifestOptions {
name: string;
host: string;
manifestSRC: string;
}
type TUseManifestReturn = [TManifest | undefined, Error | undefined];
const useManifest = (
onMicroLoaded: () => void,
{ name, manifestSRC, host }: IUseManifestOptions,
fetchOpts: any,
): TUseManifestReturn => {
const scriptId = `_react-micro-js-${name}`;
const [manifest, setManifest] = useState();
const [error, setError] = useState();
useEffect(() => {
const attachScript = (manifestData: TManifest) => {
const promises = Object.keys(manifestData.files).reduce(
(acc: any, key) => (key.endsWith('.js') ? [...acc, appendChunck(key, host, manifestData, scriptId)] : acc),
[],
);
Promise.allSettled(promises).then(onMicroLoaded).catch(setError);
};
const fetchManifest = async () => {
const manifestData = await fetch(`${host}/${manifestSRC}`, fetchOpts)
.then((res) => res.json())
.catch(setError);
attachScript(manifestData);
setManifest(manifestData);
};
if (!document.getElementById(scriptId)) {
fetchManifest();
}
}, [host, manifestSRC, onMicroLoaded]);
return [manifest, error];
};
export default useManifest;