All Questions

Coding

How do I insert a js snippet on a react application?

I get that I can simply insert the import script on some component but what about the signup function?

author Tiago Ferreira

Reply
17 Answers

Is it a next app? By the way GPT4 should deal with it pretty easily haha

writen by Kirill Rogovoy

I usually add

...do stuff with userSession
}, [userSession]}```
to my _app

writen by Kirill Rogovoy

its gatsby

writen by Tiago Ferreira

Than pattern is the same, but you need to find the top-level component in the app that’s always called and add that signup there it seems

writen by Kirill Rogovoy

right. this might seem really noob but I do I call a script from inside the useEffect? XD

writen by Tiago Ferreira

Luca Restagno (ikoichi on Twitter) shared this with me

src='<https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js>'
onLoad={() =&gt; {
console.log(_.sample([1, 2, 3, 4]))
}}
/&gt;```

writen by Tiago Ferreira

Those two are separate I think:

  1. Add the script tag to where the <head> things go in Gatsby (never used it)
  2. Call the function from the docs in useEffect

writen by Kirill Rogovoy

So I just need to make sure that the script tag is called before calling the function… Right?

writen by Tiago Ferreira

I was wondering the same recently when I wanted to import Google Analytics into my react code. I started hacking around and then realized that there is an npm component. This helped me to avoid adding the script in <head> and then calling it from the components.

FWIW I’d also ask ChatGPT for help.

writen by Pascal Bovet

I also did But I don’t think that that reflio npm package exists…

writen by Tiago Ferreira

If you include the script somewhere in <head>, it’s guaranteed that it will be loaded sooner than your useEffect executed

writen by Kirill Rogovoy

Haha.. I love how ChatGPT just made that up

writen by Pascal Bovet

And people are afraid that AI will take over coding for us in a few months.

writen by Pascal Bovet

I mean… It tricked you

writen by Tiago Ferreira

this is what I do in Inboxs

id='reflio-js'
async
src='<https://reflio.com/js/reflio.min.js>'
data-reflio='&lt;your_id&gt;'
/&gt;```

writen by Luca Restagno (ikoichi on Twitter)

async function initReflio() {
try {
if (session?.user?.email) {
await Reflio.signup(session.user.email)
}
} catch (err) {
console.error(err)
}
}


initReflio()
}, [session?.user?.email])```

writen by Luca Restagno (ikoichi on Twitter)

Just wondering, why try-catch? I thought an unhandled exception would be printed to the console anyway?

I’d just go

if (session?.user?.email) {
return
}
Reflio.signup(session.user.email)
}, [session?.user?.email])```

writen by Kirill Rogovoy

Do you want to ask a question?


Related Questions