Skip to content
Notify when GA and GTM are loaded in your React Component
Branch: master
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
src
.gitignore
.npmignore
.prettierrc
.travis.yml Set up dev Mar 15, 2019
README.md
babel.config.js
index.test.js Export default Mar 15, 2019
package-lock.json Update readme Mar 15, 2019
package.json
rollup.config.js Fix naming Mar 15, 2019
trh.png

README.md

Is Tracking ready hook

React Hook

Tiny 327 bytes React Hook that notifes you when GA or GTM is loaded in your React Component

Use requestAnimationFrame to check when the tracking code has been loaded. There's a pre-defined timeOut (default 5000) that will stop the checking automatically and report an error if you need for example to log it somewhere.

📦 Installation

npm install tracking-ready-hook --save

🚀 Load

// using es modules
import useTrackingIsLoaded from 'tracking-ready-hook'

// common.js
const useTrackingIsLoaded = require('tracking-ready-hook')

Or use script tags and globals.

<script src="https://unpkg.com/tracking-ready-hook"></script>

And then grab it off the global like so:

const useTrackingIsLoaded = trackingIsLoaded.default;

💡 Usage

Let's assume you want to send some data to GA or to the dataLayer but in order to do that you need to wait for GA or GTM to be available in window.

function App() {
  const [status, error] = useTrackingIsLoaded();
  return (
    <div className="App">
      {status ? <p>Loaded</p> : <p>Not Loaded</p>}
      {error ? <p>Error: {error.message}</p> : null}
    </div>
  );
}

Maybe more useful: run inside useEffect Hook or onClick to send data to dataLayer

function App() {
  const [status, error] = useTrackingIsLoaded();
  useEffect(() => {
    if (status) {
      window.dataLayer.push({
      ecommerce: {
			  currencyCode: 'USD',
			  impressions: [{foo: 'bar'}]
			}
		});
    }
  })
  return (
    <div className="App">
      Please track me!!!
    </div>
  );
}

API

useTrackingIsLoaded(timeout: Number); Default timeout 5000

Returns an Array of status: Boolean and error: Error Object

Tests

npm test

Legals

Released under MIT license.

You can’t perform that action at this time.