I'm trying to figure out the best way to listen to route change in Gatsby.
The things I need is to hook on an action of route change and run specific action based on previous and next route.
I've tried several ways to hook on route change:
window.location as a previous path and the location object from function props but they're equal.Is there any other way to hook on route change action and have access to both prev and next route location object?
Thank you for opening this @wsielskx
Unfortunately, at the moment onPreRouteUpdate and onRouteUpdate only pass in the new location object
What is the use case you're trying to achieve?
Gatsby V2 uses Reach Router for navigation and the Link component can pass state to the page it navigates to. It won't help if you just need a generic "the user has navigated to a new page" event but it covers most cross-page state use cases.
Here's the example from the docs:
const NewsFeed = () => (
<div>
<Link
to="photos/123"
state={{ fromNewsFeed: true }}
/>
</div>
)
const Photo = ({ location, photoId }) => {
if (location.state.fromFeed) {
return <FromFeedPhoto id={photoId} />
} else {
return <Photo id={photoId} />
}
}
Hope this helps.
If you want to make it generic you can just pass the location as the last page.
const NewsFeed = () => (
<div>
<Link
to="photos/123"
state={{ lastLocation: location }}
/>
</div>
)
It seems a bit hacky to me though. It would be better to have access to both in onPreRouteUpdate.
You could store the last location in a variable. But seems reasonable that we'd pass it in.
If there is no any other reason, probably technical, passing pre and next location is better. I can do some help.
I think this can be closed due to https://github.com/gatsbyjs/gatsby/pull/11095
Thank you, @jordanoverbye!
Most helpful comment
I think this can be closed due to https://github.com/gatsbyjs/gatsby/pull/11095