@ledgerhq/live-common
Version:
Common ground for the Ledger Live apps
60 lines • 2.13 kB
JavaScript
import React from "react";
import { appendQueryParamsToManifestURL } from "../wallet-api/utils/appendQueryParamsToManifestURL";
import { getEnv } from "@ledgerhq/live-env";
export function useManifestWithSessionId({ manifest, shareAnalytics }) {
const [id, setId] = React.useState(null);
const [loading, setLoading] = React.useState(false);
React.useEffect(() => {
let cancelled = false;
async function fetchId() {
if (!shareAnalytics || !manifest) {
setId(null);
setLoading(false);
return;
}
setLoading(true);
try {
const response = await fetch(getEnv("PROVIDER_SESSION_ID_ENDPOINT"), {
method: "GET",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
});
if (!response.ok)
throw new Error("Failed to fetch session ID");
const { providerSessionId } = await response.json();
if (!cancelled) {
setId(providerSessionId);
setLoading(false);
}
}
catch {
if (!cancelled) {
setId(null);
setLoading(false);
}
}
}
fetchId();
return () => {
cancelled = true; // avoid setting state after unmount
};
}, [shareAnalytics]);
const customizedManifest = React.useMemo(() => {
if (!manifest)
return null;
if (loading) {
return null;
}
if (id) {
const url = appendQueryParamsToManifestURL(manifest, {
externalID: id,
});
return url ? { ...manifest, url: url.toString() } : manifest;
}
return manifest;
}, [manifest, id, loading]);
return { manifest: customizedManifest, loading };
}
//# sourceMappingURL=useManifestWithSessionId.js.map