skip to Main Content

I have an app that uses an infinity scroll. Every time I reload data, I update the history.state with histroy.replaceState and the current number of pages. If I display the whole thing on the console, I don’t see any errors, the new number of pages is output. However, if I navigate to another page and then back again, history.state is undefined or starts at 0 again. Why?
I use Chrome.
Docs: https://developer.mozilla.org/en-US/docs/Web/API/History/state

const [page, setPage] = useState((history.state && history.state.page) || 0);

console.log("history.state.page " + history.state.page);

...

<SingleImage newLimit={() => {setPage(page + 11);history.replaceState({ page: page + 11 }, "");}} product={product}
    handleClickOnImageEvent={handleClickOnImageEvent}>
</SingleImage>

2

Answers


  1. The docs that you referenced state the following:

    The value is null until the pushState() or replaceState() method is used.

    Therefore on a page reload history.state will always be null.

    One possible solution you could try is to use querystring params to hold your page state. e.g.

    const url = new URL(location);
    url.searchParams.set("page", page + 11);
    history.replaceState({}, "", url);
    

    example from here: https://developer.mozilla.org/en-US/docs/Web/API/History/pushState#change_a_query_parameter

    Login or Signup to reply.
  2. You can try with localStorage

    // Save the current number pageNumberLocal
    localStorage.setItem('pageNumberLocal', currentPageNumber);
    
    // get pageNumberLocal
    const savedPageNumber = localStorage.getItem('pageNumberLocal');
    
    update starte using localstorage
    if (savedPageNumber) {
      history.replaceState({ pageNumber: parseInt(savedPageNumber) }, '');
    }
    
    update the localStorage again before navigating
    window.addEventListener('beforeunload', () => {
      localStorage.setItem('pageNumberLocal', currentPageNumber);
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search