reactjsreduxreact-routerstate

State is lost while navigating manually in a react redux application


Quick background - I have a React Redux application created using CRA CLI. There are 2 pages or routes set up in my App.js using BrowserRouter and Route of react-router-dom. One is /products which displays all products. Second is /product-details which shows details of a product.

Problem 1 - When I come to the products page, the redux state has all the products information. When I manually navigate to the url /product-details, the redux state with all the product information is lost. Why is this happening?

Problem 2 - Other than manual navigation, How do I programmatically navigate from /products to /product-details page without losing the redux state?

I have tried using the BrowserHistory as suggested in other SO answers. But that does not seem to work for both my above problems.

<Router>
    <div>
      <Route path="/" exact component={Products} />
      <Route path="/product-details" component={ProductDetails} />
    </div>
</Router>

Expected

  1. When I manually navigate to product-details from the address bar, the state from /products page should be available
  2. Should be able to programmatically navigate to the /product-details page and the state available.

Solution

  • 1) Where did you get data from the server? maybe products page? If so, you can't preserve the data when you manually navigate to the detail page. In your case, in detail page, you should send a request to the server with the product ID to get product detail information. Then it will work for sure.

    2) The Route for details page should look like this. <Route path="/product-details/:id" component={ProductDetails} /> And you can go to detail page like this. this.props.history.push('/product-details/1'); It will work for sure.