react-router-dom not updating useParmams() when Link to same path with different url

Viewed 21

It renders fine if I click the link in the <MeetNew> component from a different component, but when a <MeetNew> Link is clicked from the <User> component, the page doesn't load correctly.

on the component

const User = () => {
  let { id } = useParams()
  let res2;
  const [userInfo, setUserInfo] = useState({
    user: {},
    listItems: []
  })

  const { listItems } = userInfo

  useEffect(() => async () => {
    try {
      if (id) {
        const res2 = await axios.get(`/api/listItems/${id}`)
        setUserInfo({ listItems: res2.data })
        console.log('render')
      }
    } catch (err) {
      console.error(err)
    }
  }, [id])

  return (
  ...
  )

I feel like I'm not using useParams() correctly or useEffect correctly. When I click the link the URL change is correct, but useParams() doesn't re-render or re-mount my component.

2 Answers

I guess you are referring to pages as components? Is it possible that your id param does not change, so your useEffect is not activated, thus there is no loading of items?

The useEffect looks very suspect to me. It doesn't run any logic as part of the effect other than to return an async cleanup function. This probably isn't what you meant to implement.

Refactor the useEffect callback to declare an async function and only invoke it if there is a truthy id dependency value.

useEffect(() => {
  const getItems = async () => {
    try {
      const res2 = await axios.get(`/api/listItems/${id}`);
      setUserInfo({ listItems: res2.data });
    } catch (err) {
      console.error(err);
    }
  }

  if (id) {
    getItems();
  }
}, [id]);

What I suspect is happening is that you are using react@18 and rendering the app into a React.StrictMode component. In react@18 the StrictMode component intentionally "double-mounts" react components as a way to ensure Reusable State. The returned cleanup function runs and makes the GET request and the state is updated. The only occurs on the initial mounting/render of the component, subsequent renders occur normally. This part is just a hunch though by looking at just your code without testing a running demo.

Related