React show same list of items when browser back button is clicked

Viewed 819

I have 2 react components. The first component is a list of item. And the 2nd component is the component representing an item.

The first component fetch data from a server in the componentDidMount lifecycle method. The first time you arrive to this page, 20 items are shown. The page also have a "Show more" button. When the user clicks on that button, 20 more data are fetched.

Let's admit that the user clicks on that button. So now 40 items are shown.

The user can click on an item, and is redirect to another page with the item details.

My problem, is when the user click on the back browser button (to gack back to the list of items), the component re-render and show only 20 items. The previous state (with 40 items) is lost.

What i want is, if the current state has 40 items, and the user clicks on one of them (to see the detail's page), when he returns back (by the browser navigation), always show him the the same list before he went to the detail's page.

In other words, the navigation from the detail's page to the list page, must not re-render the list page.

I hope that my explanation is clear enough.

Thanks.

1 Answers

The problem is that when you access to the second Component the first is unmounted. You have various choices: - Use a store like Redux to retain data - Present the second component without unmounting the previous (IE: modal) - Store component state in upper state (lift state up, that resolves 90% of react pattern issues) - Store the result in localstorage - Store somewhere the NUMBER of items loaded to prevent to show outdated data

The way you intend to implement it really depends on data persistency/ux acceptance criteria, but you have a lot of choices.

Related