Gatsby: Gatsby route change listener

Created on 29 Dec 2018  路  7Comments  路  Source: gatsbyjs/gatsby

Summary

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.

Relevant information

I've tried several ways to hook on route change:

  • onRouteUpdate - unfortunately it has access only to a new route and doesn't contain any information about the previous one.
  • onPreRouteUpdate - the name of the function suggests that it is called right before the route change, but it doesn't. I've tried to use 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?

good first issue

Most helpful comment

I think this can be closed due to https://github.com/gatsbyjs/gatsby/pull/11095

All 7 comments

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!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

totsteps picture totsteps  路  3Comments

ferMartz picture ferMartz  路  3Comments

kalinchernev picture kalinchernev  路  3Comments

dustinhorton picture dustinhorton  路  3Comments

dustinhorton picture dustinhorton  路  3Comments