0

We're attempting to load an ad script - but only if a user is non-authenticated. Note: We are using Next.js

Here is how we're loading the ad script at the moment (note, this is a condensed example).

const AdContext = createContext()
export default AdContext
export const useAd = () => useContext(AdContext)

export const AdProvider = ({ children }) => {
  const { currentUserIsSilverPlus } = useAuth()

  const loadAds = useCallback(() => {
    // ... Pushes ad blocks into divs/ad placement area...
  }, [currentUserIsSilverPlus])

  const contextValues = { loadAds }

  return (
    <AdContext.Provider value={contextValues}>
      <Script
        type="text/javascript"
        src={`//external-script.js`}
        data-cfasync="false"
        onLoad={loadAds}
      />
      {children}
    </AdContext.Provider>
  )
}

I tried the following, but it doesn't quite work because when the page initially loads, currentUserIsSilverPlus is set as false (and then quickly switches to true).

  if(!currentUserIsSilverPlus) {
    return (
        <AdContext.Provider value={contextValues}>
          <Script
            type="text/javascript"
            src={`//monu.delivery/site/a/9/598bde-eb57-4f38-a35e-8d84df26769e.js`}
            data-cfasync="false"
            onLoad={loadAds}
          />
          {children}
        </AdContext.Provider>
      )
  } else {
    return (
        <AdContext.Provider value={contextValues}>
          {children}
        </AdContext.Provider>
      )
  }
}

I also tried moving the script load into useEffect, but the same issue occurred - with the script always load.

useEffect(() => {
   if(!currentUserIsSilverPlus) {
    return (
        <Script
        type="text/javascript"
        src={`//external-script.js`}
        data-cfasync="false"
        onLoad={loadAds}
      />
    )
   }
  }, [currentUserIsSilverPlus])
  
  return (
    <AdContext.Provider value={contextValues}>
      {loadAdScript()}
      {children}
    </AdContext.Provider>
  )

How can I get the script to only load when currentUserIsSilverPlus is True (despite it being initially False on load).

Edit: Adding auth code at request of a commenter.

const AuthContext = createContext()

export default AuthContext

export const AuthProvider = ({ children, isProtected = false }) => {
  const [loading, setLoading] = useState(false)
  const [userLoaded, setUserLoaded] = useState(false)
  const [currentUser, setCurrentUser] = useState(null)
  const [currentUserRole, setCurrentUserRule] = useState("Free - Bronze")
  const [currentUserIsSilverPlus, setCurrentUserIsSilverPlus] = useState(false)
  const [currentUserIsGoldPlus, setCurrentUserIsGoldPlus] = useState(false)
  const [currentUserIsDiamondPlus, setCurrentUserIsDiamondPlus] =
    useState(false)
  const [hyvorSSO, setHyvorSSO] = useState({})
  const [emailHasBeenSent, setEmailHasBeenSent] = useState(false)
  const router = useRouter()

  const updateUserInfo = useCallback(async user => {
    setHyvorSSO(HYVOR_TALK_CONFIG.sso)
    setCurrentUser(user)
    setUserLoaded(true)
    if (user) {
      const stripeRole = await getUserStripeRole(user)
      if (stripeRole) {
        setCurrentUserRule(stripeRole)
        setCurrentUserIsSilverPlus(true)
      }
      if (stripeRole === "PRO-Gold") {
        setCurrentUserIsSilverPlus(true)
        setCurrentUserIsGoldPlus(true)
      }
      if (stripeRole === "PRO-Diamond") {
        setCurrentUserIsSilverPlus(true)
        setCurrentUserIsGoldPlus(true)
        setCurrentUserIsDiamondPlus(true)
      }
    }
  }, [])

  useEffect(() => {
    registerUserUpdateEventListener(updateUserInfo)
  }, [updateUserInfo])

  useEffect(() => {
    if (isProtected && userLoaded && !currentUser) router.push("/login")
  }, [isProtected, userLoaded, currentUser, router])

  const contextValues = {
    currentUser,
    currentUserRole,
    currentUserIsSilverPlus,
    currentUserIsGoldPlus,
    currentUserIsDiamondPlus,
    hyvorSSO,
    emailHasBeenSent,
    userLoaded,
    isNotLoggedIn: userLoaded && !currentUser,
    signUp,
    signIn,
    signOut,
    manageAccount,
    resetPassword: resetUserPassword,
    sendVerificationEmail,
    changeEmail,
    startCheckoutSession,
  }

  if (loading || (isProtected && !userLoaded)) return <LoaderBaseball />

  return (
    <AuthContext.Provider value={contextValues}>
      {children}
    </AuthContext.Provider>
  )
}
2
  • Could you share your useAuth code, too? That would help to identify your problem Commented Apr 3, 2022 at 5:07
  • @NickVu - I added a condensed version of it to the original post. Commented Apr 3, 2022 at 5:27

1 Answer 1

0

You can check with userLoaded before checking currentUserIsSilverPlus

const AdContext = createContext()
export default AdContext
export const useAd = () => useContext(AdContext)

export const AdProvider = ({ children }) => {
  const { currentUserIsSilverPlus, userLoaded } = useAuth()

  const loadAds = useCallback(() => {
    // ... Pushes ad blocks into divs/ad placement area...
  }, [currentUserIsSilverPlus])

  const contextValues = { loadAds }

  
  //if user data is not loaded yet, we don't need to have that script
  //and in the meanwhile, we also check `currentUserIsSilverPlus`  
  return (
    <AdContext.Provider value={contextValues}>
      {userLoaded && !currentUserIsSilverPlus && <Script
        type="text/javascript"
        src={`//external-script.js`}
        data-cfasync="false"
        onLoad={loadAds}
      />}
      {children}
    </AdContext.Provider>
  )
}
Sign up to request clarification or add additional context in comments.

2 Comments

Unfortunately, that didn't fix the issue. I'm starting to think that next/script gets "injected" into the DOM - so once it's there, it needs to be manually removed.
Did you try to put console.log to check userLoaded value? I think it'd help to narrow down where problem is @JeremyE

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.