I have an app which has GTM tracking. I'm currently checking when a route has taken place and pushing a page_view event to the dataLayer.
The problem I'm having is getting the dataLayer to push when the app loads initially. I have a back button which when clicked goes back to the home screen and fires an event but I can't get it to fire when the app loads initially. I can explicitly add the push event to the home ponent when it mounts, which will work but when I click the go back button it will fire twice.
Here's my code does anyone know how to get this to work when the app loads initially without duplicating the push?
ponentDidUpdate(prevProps) {
if (this.props.path !== prevProps.path)
{
this.routeChange();
}
}
routeChange(){
window.dataLayer.push({
event: "page_view",
url: this.props.path
});
}
I have an app which has GTM tracking. I'm currently checking when a route has taken place and pushing a page_view event to the dataLayer.
The problem I'm having is getting the dataLayer to push when the app loads initially. I have a back button which when clicked goes back to the home screen and fires an event but I can't get it to fire when the app loads initially. I can explicitly add the push event to the home ponent when it mounts, which will work but when I click the go back button it will fire twice.
Here's my code does anyone know how to get this to work when the app loads initially without duplicating the push?
ponentDidUpdate(prevProps) {
if (this.props.path !== prevProps.path)
{
this.routeChange();
}
}
routeChange(){
window.dataLayer.push({
event: "page_view",
url: this.props.path
});
}
Share
Improve this question
edited Jul 17, 2018 at 10:06
Tholle
113k22 gold badges208 silver badges197 bronze badges
asked Jul 17, 2018 at 9:19
user3486427user3486427
4841 gold badge11 silver badges21 bronze badges
1 Answer
Reset to default 3You could create your history
object manually outside of the Router
and listen to changes on that and also send an event directly when the file loads.
Example
import createBrowserHistory from "history/createBrowserHistory";
const history = createBrowserHistory();
history.listen(location => {
const { pathname } = location;
window.dataLayer.push({
event: "page_view",
url: pathname
});
});
window.dataLayer.push({
event: "page_view",
url: window.location.pathname
});
function App() {
return (
<Router history={history}>
{/* ... */}
</Router>
);
}