Home > Enterprise >  React router doesn't refresh page
React router doesn't refresh page

Time:03-22

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.

CodePudding user response:

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]);
  • Related