Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

"shouldUpdateScroll" "getSavedScrollPosition" always returns NULL? #23842

Closed
zuzy-dev opened this issue May 6, 2020 · 9 comments
Closed

"shouldUpdateScroll" "getSavedScrollPosition" always returns NULL? #23842

zuzy-dev opened this issue May 6, 2020 · 9 comments
Labels
topic: core Relates to Gatsby's core (e.g. page loading, reporter, state machine) type: question or discussion Issue discussing or asking a question about Gatsby

Comments

@zuzy-dev
Copy link

zuzy-dev commented May 6, 2020

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

@zuzy-dev zuzy-dev added the type: question or discussion Issue discussing or asking a question about Gatsby label May 6, 2020
@gatsbot gatsbot bot added the status: triage needed Issue or pull request that need to be triaged and assigned to a reviewer label May 6, 2020
@vladar vladar added status: needs core review Currently awaiting review from Core team member topic: core Relates to Gatsby's core (e.g. page loading, reporter, state machine) and removed status: triage needed Issue or pull request that need to be triaged and assigned to a reviewer labels May 6, 2020
@blainekasten
Copy link
Contributor

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 blainekasten removed the status: needs core review Currently awaiting review from Core team member label May 21, 2020
@adamschwartz
Copy link

@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!

@zuzy-dev
Copy link
Author

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!

@s-herbert
Copy link

s-herbert commented Jul 1, 2020

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

@blainekasten
Copy link
Contributor

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?

@magnusarinell
Copy link

magnusarinell commented Jul 29, 2020

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.

@magnusarinell
Copy link

magnusarinell commented Jul 29, 2020

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

@blimpmason
Copy link

blimpmason commented Sep 24, 2020

@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.

@gristleism
Copy link

@magnusarinell Thank you so much for this code, I've used this on my most recent project and it's working great. I did have to make one small tweak to handle a situation where results.sort() would put the @@scroll|/|initial key in the wrong place so its scroll value would be used instead of the most recent visit to the page.

I added the following after results.sort():

  if (results.includes("@@scroll|/|initial")) {
    results.unshift(results.pop())
  }

Which would make sure to move the @@scroll|/|initial key to the beginning of the array.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
topic: core Relates to Gatsby's core (e.g. page loading, reporter, state machine) type: question or discussion Issue discussing or asking a question about Gatsby
Projects
None yet
Development

No branches or pull requests

8 participants