Gatsby: "shouldUpdateScroll" "getSavedScrollPosition" always returns NULL?

Created on 6 May 2020  Â·  8Comments  Â·  Source: gatsbyjs/gatsby

Summary

When trying to get the scroll position with getSavedScrollPosition in gatsby-browser.js the output of console.log is always null. I’m not sure if this is correct?

I’m trying to exclude one page/route from the standard „start at top of the page“-behaviour.
The reason for this is that I have a long list of articles on this page. When the user clicks on a <Link> somewhere down on this list, he is taken to the top of the article (which is wanted in this case). But when he then clicks the close/back-link of the on-page-navigation he is taken back to the top of the listing-page and has to scroll down all the way again to where he left off. (When he uses the back-button of the browser, instead of the on-page-navigation, he is correctly taken back to right scroll position of the previous page.)
I opted out of using browser-history-api because I also have next/prev-links on the article and want the user to always return to the listing-page when he is using the close/back-link.

Steps to reproduce

Go to this Gatsby-Starter-Sandbox, reload the preview.
Open up the console below and navigate the page.
(Beside editing gatsby-browser.js I only added some paragraphs and changed headlines on the pages)

Changing routerProps to prevRouterProps will return the right coordinates for currentPosition from SessionStorage. But not for queriedPosition.

Expected result

const queriedPosition = getSavedScrollPosition({ pathname: `/page-2/` })

should give an Array of the last saved coordinates from the given location.
As described in the shouldUpdateScroll documentation which then can be used to scroll to the right position on the given route.

Actual result

const queriedPosition = getSavedScrollPosition({ pathname: `/page-2/` })`

returns null. (I also tried /page-2, and even page-2, or /)

Therefore every new page is scrolled to top on navigation, even when trying to go to the last scroll position of a queried route via window.scrollTo(...(queriedPosition || [0, 0])).

SessionStorage is populated with the right saved and actual @@scroll-values.

File contents (if changed)

gatsby-config.js: N/A
package.json: N/A
gatsby-node.js: N/A
gatsby-browser.js:

exports.shouldUpdateScroll = ({
  routerProps: { location },
  // routerProps returning NULL.
  // -------------
  // Using prevRouterProps returns scroll coordinates of last route
  // comment out next line for demonstration
  // prevRouterProps: { location },
  getSavedScrollPosition
}) => {
  const currentPosition = getSavedScrollPosition(location)
  const queriedPosition = getSavedScrollPosition({ pathname: `/page-2/` })

  console.log("currentPosition result:", currentPosition)
  console.log("queriedPosition result:", queriedPosition)

  //window.scrollTo(...(queriedPosition || [0, 0]))

  return false
}

gatsby-ssr.js: N/A

frontend-core question or discussion

Most helpful comment

@blainekasten Thank you!

I had the same issue and your suggestion worked for me.

It looks like the docs for shouldUpdateScroll may be incorrect then:

image

I suspect that’s how OP got their code as well. Hope this helps!

All 8 comments

Hey @lucasdon,

It looks like you are using the API incorrectly. It requires two arguments, first the location prop, and the then key of the scroll state you are trying to grab.

Typically you would want to call it like this:

getSavedScrollPosition(routerProps.location, routerProps.location.key)

Try that out and let me know if it's not working. Thanks!

@blainekasten Thank you!

I had the same issue and your suggestion worked for me.

It looks like the docs for shouldUpdateScroll may be incorrect then:

image

I suspect that’s how OP got their code as well. Hope this helps!

Thank you both!

@adamschwartz Good to hear. Thought I was going crazy.

Could you share a little bit more about your solution? That would be very beneficial as I’m quite new to this Gatsby-thing.

Have a nice weekend!

I will say I ended up here because I also followed the Docs and only saw null returned

I am curious to hear what everyone is using this API for? I personally would love to remove this API. It feels like a footgun to me. Mind sharing your use cases?

Hi @blainekasten,

Please keep this API! I'm using it at https://www.istoriez.com when navigating back to start (on small screens where you get the bottom nav) from another page, such as a bedtime story. Or at least that is my plan, but I couldn't get it to work due to the errors in the documentation. Hope to get things working after you've clarified the usage. Thanks

Edit: Wait a minute, I don't know the key of the saved scroll state. The routerProps.location.key has a new value not yet saved in session storage.

I couldn't get it working so I solved it manually doing:

const getLatestSavedScrollPosition = (pathname) => {
    let n = sessionStorage.length;
    let i = 0;

    const partialKey = `@@scroll|${pathname}|`

    let results = [];

    while (++i < n) {
        const key = sessionStorage.key(i);

        if (key.includes(partialKey)) {
            results.push(key)
        }
    }

    if (results.length === 0) {
        return 0;
    }

    results.sort();

    return sessionStorage.getItem(results[results.length - 1]);
}

Called from shouldUpdateScroll like this:

        const currentPosition = getLatestSavedScrollPosition(routerProps.location.pathname)

Edit: Code is now available at https://github.com/magnusarinell/istoriez.com

@blainekasten this API is crucial for orchestrating page transitions. See @ryanwiemer 's page transition example repo here for reference: https://github.com/ryanwiemer/gatsby-using-page-transitions

I'm having the same issue in which the saved position is always returned as 0 or null despite the fact that the scroll positions are saved in session storage.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ferMartz picture ferMartz  Â·  3Comments

dustinhorton picture dustinhorton  Â·  3Comments

rossPatton picture rossPatton  Â·  3Comments

signalwerk picture signalwerk  Â·  3Comments

andykais picture andykais  Â·  3Comments