Redux state clear on page changes

Viewed 2086

I have react container which is connected to an 'items' reducer. By navigating to another page, such as user profile, I want to get the user's 'items' list from the server and change the state. The issue is, that if I navigate from the main page, the items state is already filled with data, then on the user page I see the old for couple of seconds until it is changed from the api call. I was thinking about creating new reducer for the userItems, but then, if I will navigate to another user page, I will see the previous userItems for couple of seconds.

The solution is to fetch the data and keep it only in the react component state? And not redux?

Thanks.

2 Answers

I think the two better options for tackling this problem are:

  1. If you really want your redux state to only contain the 'items' relative to the page you are looking at, you could include a 'fetching' attribute in your state, and show a loading bar while you call the API and update your state

  2. You could store a user's 'items' in an array inside the user object in your state, and then display user.items for the relevant user. You don't necessarily have to have all users 'items' in the redux store at all times. If you were to do this without a loading indicator, the user page would load with no items, and the items would appear once the API was called and the Redux state updated

@Morgan Danger Hall has the right idea in their answer.

Depending on how often you go back and forth between users, you may also want to consider keeping all of the items for all users in the items array, and then adding an activeUser attribute to your state with the id of the user currently being viewed. Then you would have the display component filter the items list by the activeUser.

This could help with performance if you end up going back and forth between users, as long as you are comfortable with cacheing the results from previous fetches.

Just make sure you understand how volatile your items list is. If it's a rapidly-changing list, you might not want to cache it at all!

Related