Skip to content

Commit

Permalink
Merge pull request #108 from Nosto/simplify-hook-state
Browse files Browse the repository at this point in the history
Simplify hook state
  • Loading branch information
timowestnosto authored Aug 16, 2024
2 parents 34e931a + 376619d commit cbd2424
Showing 1 changed file with 9 additions and 10 deletions.
19 changes: 9 additions & 10 deletions src/hooks/useLoadClientScript.ts
Original file line number Diff line number Diff line change
@@ -1,31 +1,30 @@
import { useState, useMemo, useEffect } from "react"
import { useState, useEffect } from "react"
import { isNostoLoaded } from "../components/helpers"
import type { NostoClient } from "../types"
import type { NostoProviderProps } from "../components/NostoProvider"

type NostoScriptProps = Pick<NostoProviderProps, "account" | "host" | "shopifyMarkets" | "loadScript">

export function useLoadClientScript(props: NostoScriptProps) {
const { host, account, shopifyMarkets, loadScript = true } = props
const [clientScriptLoadedState, setClientScriptLoadedState] = useState(false)
const clientScriptLoaded = useMemo(() => clientScriptLoadedState, [clientScriptLoadedState])
const { host = "connect.nosto.com", account, shopifyMarkets, loadScript = true } = props
const [clientScriptLoaded, setClientScriptLoaded] = useState(false)

useEffect(() => {
const scriptOnload = () => {
function scriptOnload() {
// Override for production scripts to work in unit tests
if ("nostoReactTest" in window) {
window.nosto?.reload({
site: "localhost"
})
}
setClientScriptLoadedState(true)
setClientScriptLoaded(true)
}

// Create script element
function createScriptElement(urlPartial: string) {
const scriptEl = document.createElement("script")
scriptEl.type = "text/javascript"
scriptEl.src = `//${(host || "connect.nosto.com")}${urlPartial}`
scriptEl.src = `//${host}${urlPartial}`
scriptEl.async = true
scriptEl.setAttribute("nosto-client-script", "")
return scriptEl
Expand Down Expand Up @@ -63,8 +62,8 @@ export function useLoadClientScript(props: NostoScriptProps) {
existingScript?.getAttribute("nosto-market-id") !== marketId

if (!existingScript || existingScriptAttributes) {
if (clientScriptLoadedState) {
setClientScriptLoadedState(false)
if (clientScriptLoaded) {
setClientScriptLoaded(false)
}

const nostoSandbox = document.querySelector("#nosto-sandbox")
Expand All @@ -81,7 +80,7 @@ export function useLoadClientScript(props: NostoScriptProps) {
document.body.appendChild(script)
}
}
}, [clientScriptLoadedState, shopifyMarkets])
}, [clientScriptLoaded, shopifyMarkets])

return { clientScriptLoaded }
}

0 comments on commit cbd2424

Please sign in to comment.