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();
}, [])
Issue
The issue is the
useEffecthook 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
useSearchParamshook instead of theuseLocationhook to read/access theidquery parameter. Addidto theuseEffecthook's dependency array so the component reruns theuseEffectcallback when theidquery parameter value changes.Example: