Home > Software design >  Watch route params changes, re-fetch data on change
Watch route params changes, re-fetch data on change

Time:02-15

How can I react to route param changes? I want to re-fetch data for new params of my item. For e.g whenever I move from /1 to /2 I want to fetch the data for id 2. How can I do this using router v6?

import './App.css';
import { useParams } from "react-router-dom";

function Item() {
  const { id } = useParams();

    return (
      <div className="test">
       test of nested route id: { id };
      </div>
    );
  }
  
  export default Item;
  

CodePudding user response:

You can detect changes with useEffect

import './App.css';
import { useParams } from "react-router-dom";
import {useEffect} from "react"

function Item() {
  const { id } = useParams();

  useEffect(() => {
    //...your function goes here
  }, [id])

    return (
      <div className="test">
       test of nested route id: { id };
      </div>
    );
  }

export default Item;

CodePudding user response:

Routing like this.

import {Route, Routes} from "react-router-dom";
import Item from "./components/Item";

function App() {
    return (
        <Routes>
            <Route path="/main/:id" element={<Item/>}/>
        </Routes>
    );
}

export default App;

Then use params.

import './App.css';
import { useParams } from "react-router-dom";

function Item() {
  const { id } = useParams();

    return (
      <div className="test">
       test of nested route id: { id };
      </div>
    );
  }

export default Item;
  • Related