Reputation: 1545
Gatsby/React Project wont recongnize ssr script tag cloudinary variable but if I open up the inspect tool and type cloudinary and hit enter the entire function is there. Even if I place cloudinary console log in a click event it still returns undefined, same with a useEffect.
Any Ideas why I can't access cloudinary.
Thanks ahead of time
Here is the ssr
import React from "react"
export const onRenderBody = ({ setHeadComponents }, pluginOptions) => {
setHeadComponents([
<script
key="cloudinary"
src="https://widget.cloudinary.com/v2.0/global/all.js"
type="text/javascript"
async
/>,
])
}
Here is the entrie code of the page, I only have helmet there when I turn off the ssr part
import React, { useEffect, useState } from "react"
import Layout from "../components/layout"
import Footer from "../components/Footer"
import { Helmet } from "react-helmet"
const Concepts = ({ data, location }) => {
const clickMe = () => {
console.log(cloudinary) //returns undefined
}
return (
<Layout location={location}>
<Helmet>
<script
src="https://widget.cloudinary.com/v2.0/global/all.js"
type="text/javascript"
></script>
</Helmet>
<button onClick={clickMe}>test</button>
<Footer />
</Layout>
)
}
export default Concepts
The point of testing for cloudinary is because adding the button and this script was returning undefined.
var myWidget = cloudinary.createUploadWidget({
cloudName: 'my_cloud_name',
uploadPreset: 'my_preset'}, (error, result) => {
if (!error && result && result.event === "success") {
console.log('Done! Here is the image info: ', result.info);
}
}
)
Upvotes: 0
Views: 101
Reputation: 29320
You have multiple ways of adding a <script>
in your <header>
, both setHeadComponents and <Helmet>
are perfectly valid, in addition, if you inspect (as you said) the output code, it should appear. So that part looks perfect to me.
In your case, cloudinary
is not defined because belongs to the window
global object. Something like this should work:
import React, { useEffect, useState } from "react"
import Layout from "../components/layout"
import Footer from "../components/Footer"
import { Helmet } from "react-helmet"
const Concepts = ({ data, location }) => {
const clickMe = () => {
if(typeof window !== 'undefined'){
console.log(window.cloudinary) //
let widget = window.cloudinary.createUploadWidget({
cloudName: `your cloudName`,
uploadPreset: `your upload preset`},
(error, result) => {
if (!error && result && result.event === "success") {
console.log(result.info.url);
}});
widget.open() //
}
}
return (
<Layout location={location}>
<Helmet>
<script
src="https://widget.cloudinary.com/v2.0/global/all.js"
type="text/javascript"
></script>
</Helmet>
<button onClick={clickMe}>test</button>
<Footer />
</Layout>
)
}
Further resources:
Upvotes: 1