} /> And when I'm in 'http://localhost:3000/Profile?id=11', the Profile component will get t" /> } /> And when I'm in 'http://localhost:3000/Profile?id=11', the Profile component will get t" /> } /> And when I'm in 'http://localhost:3000/Profile?id=11', the Profile component will get t"/>

Navigate route in reactjs doesn't work as expected

671 views Asked by At

I have a route

<Route path="/Profile" element={<Profile />} />

And when I'm in 'http://localhost:3000/Profile?id=11', the Profile component will get the id query parameter and render user data respectively. But when I try to navigate to another user using useNavigate

navigate(`/Profile?id=${userId}`)

It just changed the URL ('http://localhost:3000/Profile?id=15') and didn't reload the page and new user data too. So can you tell me why and how to fix it.

Update: Profile component is like

let location = useLocation();
let query = new URLSearchParams(location.search);
const navigate = useNavigate();

useEffect(() => {
  const getUser = async () => {
    const res = await axios.get('http://localhost:8082/api/getUserInfo', {
      params: {
        id: query.get("id"),
      },
      withCredentials: true,
    })
    setVisitor(res.data.visitor);
    setUser(res.data.user);
  }
  getUser();
}, [])
1

There are 1 answers

0
Drew Reese On

Issue

The issue is the useEffect hook runs only once when the component mounts. The component doesn't remount if the route path doesn't change, it will only rerender when route path parameters or the URL query search changes. The component isn't handling these parameters updating during the life of the component.

Solution

Use the useSearchParams hook instead of the useLocation hook to read/access the id query parameter. Add id to the useEffect hook's dependency array so the component reruns the useEffect callback when the id query parameter value changes.

Example:

const [searchParams] = useSearchParams();
const navigate = useNavigate();

const id = searchParams.get("id");

useEffect(() => {
  const getUser = async () => {
    const res = await axios.get('http://localhost:8082/api/getUserInfo', {
      params: { id },
      withCredentials: true,
    })
    setVisitor(res.data.visitor);
    setUser(res.data.user);
  }
  getUser();
}, [id]); // <-- pass id as dependency here