fix: handles errors while loading surveys pkg (#2489)

This commit is contained in:
Anshuman Pandey
2024-04-19 12:38:13 +05:30
committed by GitHub
parent 687e12ad9b
commit 06f2d85f8e
2 changed files with 38 additions and 13 deletions

View File

@@ -1,4 +1,4 @@
import { useEffect, useMemo } from "react";
import { useCallback, useEffect, useMemo } from "react";
import { SurveyInlineProps, SurveyModalProps } from "@formbricks/types/formbricksSurveys";
@@ -16,15 +16,29 @@ declare global {
export const SurveyInline = (props: Omit<SurveyInlineProps, "containerId">) => {
const containerId = useMemo(() => createContainerId(), []);
const renderInline = useCallback(
() => window.formbricksSurveys.renderSurveyInline({ ...props, containerId }),
[containerId, props]
);
useEffect(() => {
if (typeof window !== "undefined") {
const renderInline = () => window.formbricksSurveys.renderSurveyInline({ ...props, containerId });
if (!window.formbricksSurveys) {
loadSurveyScript().then(renderInline);
} else {
renderInline();
async function loadScript() {
if (typeof window !== "undefined") {
if (!window.formbricksSurveys) {
try {
await loadSurveyScript();
renderInline();
} catch (error) {
console.error("Failed to load the surveys package: ", error);
}
} else {
renderInline();
}
}
}
}, [containerId, props]);
loadScript();
}, [containerId, props, renderInline]);
return <div id={containerId} className="h-full w-full" />;
};

View File

@@ -1,10 +1,21 @@
export const loadSurveyScript: () => Promise<void> = async () => {
try {
const scriptContent = await (await fetch("/api/packages/surveys")).text();
document.head.appendChild(
Object.assign(document.createElement("script"), { textContent: scriptContent })
);
const response = await fetch("/api/packages/surveys");
if (!response.ok) {
throw new Error("Failed to load the surveys package");
}
const scriptContent = await response.text();
const scriptElement = document.createElement("script");
// append the script content to the script element
scriptElement.textContent = scriptContent;
// append the script element to the head of the document
document.head.appendChild(scriptElement);
} catch (error) {
console.error("Failed to load the surveys package:", error);
// handle when loading the script
throw error;
}
};