1

I have this hook which on mounting of the component requests data and on unmounting clears store for given entity:

export const useFetch = () => {
  const dispatch = useDispatch()
  const data = useSelector(entitySelector.data) // Selector which returns data from store
  const status = useSelector(entitySelector.status) // Selector which returns request status; idle, pending, fulfilled, rejected
  useEffect(() => {
    if (status === 'idle') {
      dispatch(entityActions.request(id))
    }
    return () => {
      dispatch(entityActions.reset())
    }
  }, [])
  return data
}

which in the component is used like:

const data = useFetch()

On the initial load of the component, everything works as expected, data is requested and then loaded and returned object contains data within the store. When component is unmounted reset action is called and store is cleared.

If I switch to other route and back everything works as expected. However, if I open link with the same view, or just save file and let CRA module reloader refresh the component, the useEffect part for fetching data is not called and no data is rendered.

Routes are nested within other component like this:

<div>
  <ul>
    <li>
      <Link to="/foo">Foo</Link>
    </li>
    <li>
      <Link to="/bar">Bar</Link>
    </li>
  </ul>

  <Route path="/foo" component={Foo} />
  <Route path="/bar" component={Bar} />
</div>

How do I fix this so that useEffect fetching piece is called upon loading same route again?

Kunok
  • 8,089
  • 8
  • 48
  • 89
  • does this component go through a HOC? – dee Jul 15 '21 at 10:19
  • @deechris27 No custom HOCs – Kunok Jul 15 '21 at 10:32
  • Does adding the status var to the dependency array in the useEffect resolve the issue? With an empty dependency array, it's essentially saying, "Just execute this one time." – Budhead2004 Jul 16 '21 at 12:57
  • I suggest you to take a look at https://stackoverflow.com/questions/38839510/forcing-a-react-router-link-to-load-a-page-even-if-were-already-on-that-page for when you open the links of the same view. – Danny Ouellet Jul 21 '21 at 15:25
  • https://codesandbox.io/s/dreamy-leaf-keyyu?file=/src/App.js.. Here is a less detailed version.. I can't reproduce either of the issues... Please try to reproduce and update the question accordingly – ChandraKumar Jul 27 '21 at 06:21

1 Answers1

1

Try to add the entitySelector, status and id to useEffect dependencies array and maybe remove the 'dispatch(entityActions.reset())' from this return fn

export const useFetch = () => {
  const dispatch = useDispatch()
  const data = useSelector(entitySelector.data) // Selector which returns data from store
  const status = useSelector(entitySelector.status) // Selector which returns request status; idle, pending, fulfilled, rejected
  useEffect(() => {
    if (status === 'idle') {
      dispatch(entityActions.request(id))
    }
    dispatch(entityActions.reset())
  }, [entitySelector, status, id])
  return data
}