I'm trying to integrate Snipcart into Gatsby (v2).
I edit the html.js
file like this:
import React from "react"
import PropTypes from "prop-types"
export default class HTML extends React.Component {
render() {
return (
<html {...this.props.htmlAttributes}>
<head>
<meta charSet="utf-8" />
<meta httpEquiv="x-ua-compatible" content="ie=edge" />
<meta
name="viewport"
content="width=device-width, initial-scale=1, shrink-to-fit=no"
/>
{this.props.headComponents}
{/* Snipcart */}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<script src="https://cdn.snipcart.com/scripts/2.0/snipcart.js" id="snipcart" data-api-key="UF45pIjZjAtZWJkYS00MGEwLWIxZWEtNjljZThjNTRiNjA4NjM2NDg1MzAzMzQyNfDrr48"></script>
<link href="https://cdn.snipcart.com/themes/2.0/base/snipcart.min.css" type="text/css" rel="stylesheet" />
</head>
<body {...this.props.bodyAttributes}>
{this.props.preBodyComponents}
<div
key={`body`}
id="___gatsby"
dangerouslySetInnerHTML={{ __html: this.props.body }}
/>
{this.props.postBodyComponents}
</body>
</html>
)
}
}
HTML.propTypes = {
htmlAttributes: PropTypes.object,
headComponents: PropTypes.array,
bodyAttributes: PropTypes.object,
preBodyComponents: PropTypes.array,
body: PropTypes.string,
postBodyComponents: PropTypes.array,
}
What works:
If I create a div:
<a href="#" class="snipcart-edit-profile">
Edit profile
</a>
Snipcart works and opens the user profile when clicked.
What does not work:
When I want to use the public API, for example if I call:
Snipcart.api.user.logout()
in a function.
=> error 'Snipcart' is not defined no-undef
How to have the global Snipcart object in all my app?
no-undef
is a linter error and not a runtime one. So it doesn't indicate that Snipcart isn't available when your code run.
If it wasn't available, you would get this error in your browser's console: ReferenceError: Snipcart is not defined
.
If you're using eslint
, you can add a global variable like this in your eslint config:
{
"globals": {
"Snipcart": false
}
}
Alternatively, you can add a comment in the file where you use Snipcart's API: /* global Snipcart:false */
The Snipcart
object will only be available in the browser so you should make sure not to call those functions while Gatsby is pre-rendering your website. That means you should only call Snipcart.api.*
functions thought Gatsby's Browser API and not the SSR or Node APIs.
Also to make sure you're calling Snipcart's API only after its script is fully loaded, you can check the snipcart.ready
event:
document.addEventListener('snipcart.ready', function() {
// any Snipcart.api.* call
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With