React strategies for maintaining page state during routing

On a page, I have a list with a drop-down to filter by category. The page initially shows all categories and only 10 items. There is a load more button to show more items. A user can click on an item which navigates to the item page.

The problem is that the list page resets when a user hits the back button from the item page. Category filters are lost along with additional loaded items and scroll position.

I’m using flow-router. This must be a common problem so I was wondering what strategies people are implementing.

I might be wrong but I thought hitting the back button is like refreshing the page, and it won’t contain the previous props. one solution I can think of is you can preserve those props in the localstorage of the browser

Store the state outside of the react component (Session, ReactiveDict or ReactiveVars) and then depend on the state in your react component via getMeteorData.

In addition to storing the data in a local collection or reactive dict, you can also put it in the router’s query params. This makes sense to me since one might want to bookmark a set of search filters and come back to them later.

1 Like

For query params, are you suggesting the following?

  1. Store my category, limit, etc. in query params.
  2. Use FlowRouter.triggers.exit to store them along with the body.scrollTop.
  3. When FlowRouter.triggers.enter fires for my original list page, I would add the original query params for category and limit.
  4. Use setTimeout to animate the scrollTop as suggested here in the flow-router guide. This requires the use of SubsManager.

Yes, and here is how i would deal with the scroll position:

  1. Update the query params as the user is scrolling (but make sure to replace them in a way that doesn’t add to the browser history)
  2. When the list loads inspect the params once to see where you need to scroll to (do this only once, not reactively, so that the above updating doesn’t cause a loop)
  3. After the content loads, use the param from (2) to scroll to the right item in the list

Do you think that would work for you?

It should work. I don’t think it’s necessary to capture the scroll position until the user clicks a link because it can be captured with the exit trigger. According to Kadira, the key is to use SubsManager to insure quick page re-loads.

1 Like