From bf74b243f4f5ec57d23a8ec13e84243e320ee63b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Timo=20Westk=C3=A4mper?= Date: Thu, 15 Aug 2024 14:29:35 +0300 Subject: [PATCH] Add validation for recommendationComponent --- spec/nosto.load.spec.tsx | 20 ++++++++++++++++++++ src/components/NostoProvider.tsx | 8 +++++++- 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/spec/nosto.load.spec.tsx b/spec/nosto.load.spec.tsx index 91617a8..14c3850 100644 --- a/spec/nosto.load.spec.tsx +++ b/spec/nosto.load.spec.tsx @@ -27,6 +27,26 @@ describe("Nosto client script loading", () => { expect(document.querySelector("[nosto-client-script]")).toBeInTheDocument() }) + it("throws error on invalid recommendationComponent", () => { + expect(() => { + render( + + + + ) + }).toThrowError() + }) + + it("access valid React elements in recommendationComponent", () => { + render( + }> + + + ) + + expect(document.querySelector("[nosto-client-script]")).toBeInTheDocument() + }) + it("Shopify markets script", () => { render( diff --git a/src/components/NostoProvider.tsx b/src/components/NostoProvider.tsx index ce9789d..0e5b782 100644 --- a/src/components/NostoProvider.tsx +++ b/src/components/NostoProvider.tsx @@ -72,8 +72,14 @@ export default function NostoProvider(props: NostoProviderProps) { // Pass currentVariation as empty string if multiCurrency is disabled const currentVariation = multiCurrency ? props.currentVariation : "" + if (recommendationComponent && !isValidElement(recommendationComponent)) { + throw new Error( + "The recommendationComponent prop must be a valid React element. Please provide a valid React element." + ) + } + // Set responseMode for loading campaigns: - const responseMode = isValidElement(recommendationComponent) ? "JSON_ORIGINAL" : "HTML" + const responseMode = recommendationComponent ? "JSON_ORIGINAL" : "HTML" const { clientScriptLoaded } = useLoadClientScript(props)