From 06f2d85f8e6658989c90fd474f525dcafa598b7e Mon Sep 17 00:00:00 2001 From: Anshuman Pandey <54475686+pandeymangg@users.noreply.github.com> Date: Fri, 19 Apr 2024 12:38:13 +0530 Subject: [PATCH] fix: handles errors while loading surveys pkg (#2489) --- packages/ui/Survey/index.tsx | 30 ++++++++++++++++++++-------- packages/ui/Survey/lib/loadScript.ts | 21 ++++++++++++++----- 2 files changed, 38 insertions(+), 13 deletions(-) diff --git a/packages/ui/Survey/index.tsx b/packages/ui/Survey/index.tsx index 414ed27a52..6d8b2c37e3 100644 --- a/packages/ui/Survey/index.tsx +++ b/packages/ui/Survey/index.tsx @@ -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) => { 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
; }; diff --git a/packages/ui/Survey/lib/loadScript.ts b/packages/ui/Survey/lib/loadScript.ts index 196978a185..c9138d9ecc 100644 --- a/packages/ui/Survey/lib/loadScript.ts +++ b/packages/ui/Survey/lib/loadScript.ts @@ -1,10 +1,21 @@ export const loadSurveyScript: () => Promise = 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; } };