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
The docs that you referenced state the following:
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.
example from here: https://developer.mozilla.org/en-US/docs/Web/API/History/pushState#change_a_query_parameter
You can try with localStorage