Tomas Sinkevičius
Tomas Sinkevičius

Reputation: 88

React router doesn't refresh page

I have two different routes that are using the same component.


    <BrowserRouter>
      <Routes>  
        <Route path="/produktai" element={<Products />}/>
        <Route path="/produktai/:productId" element={<Products />} />
      </Routes>
    </BrowserRouter>

I'm using Link from react to switch between pages and get id's from


    const pathname = useLocation().pathname;

to perform rest api's.

For example, when i change pages using Link from /products to /products/2, url changes but the problem is that page doesn't refresh as it should. Problem solves if i'm using a tag with href as it always reloads page unlike smooth react Link functionality but i don't think that's a good solution.

Upvotes: 2

Views: 6262

Answers (2)

Cansin
Cansin

Reputation: 11

There is a better approach for this issue. Give unique keys like below.

    <Route path="/all-reports">
        <ReportsPage key="1" />
    </Route>
    <Route path="/shared-reports">
        <ReportsPage key="2" mode="shared" />
    </Route>
    <Route path="/owned-reports">
        <ReportsPage key="3" mode="owned" />
    </Route>

Upvotes: 1

Drew Reese
Drew Reese

Reputation: 202854

Even though the route path changes you are still rendering the same Products component. If you need to run some logic when the path changes, or more likely, when the productId route param updates, then you should use an useEffect hook with the productId route param as a dependency.

Example:

const { productId } = useParams();

useEffect(() => {
  if (productId) {
    // Perform rest api call and response handling
  }
}, [productId]);

Upvotes: 2

Related Questions