use-fetch
use-fetch copied to clipboard
Question: notify components of cache change
Thank you for the great library!
I have a question around a more complex, but probably common use case of multiple use-fetch hooks in a component tree. Maybe you have run into this before.
Suppose you have a todo app, where the header contains a count of open todos. This count comes from a use-fetch hook /api/todos and looks at the resulting data.length. There's a child component which renders a list of the todos using the same API, but a different hook. If I close one of the open todos in the list, and refetch, the list will update, but the count will be stale, even though the hooks read from the same caching key. At least, I believe that is true?
Do you have any recommendations for notifying the parent component that the cache is updated? The simplest approach would be to pass down the doFetch from the parent to child. But, this gets pretty messy if there's lots of nesting. It gets even more complicated if the API that has the count is different than the one which has the list.
Thanks!
Hey
As you suggest, the simplest way is to pass down doFetch. If there's a lot of nesting, I'd just use React's context and consume it in the child (or a level above it) with useContext in order to avoid having pass the props a thousand levels down.
I did consider having useFetch instances subscribe to cache changes, but opted out for some reason I can't remember, probably laziness :P Maybe in the future.
Haha gotcha. Yeah I went with the useContext route.
It would definitely be cool if you could specify refetchQueries (or just tap in onSuccess), and then have the hook subscribe to cache updates