How to imperatively get a single resource
I'm wondering what is the best way to go about fetching a single resource in an imperative manner. For example, when my phone receives a notification which is carrying an id, I want to invoke a fetch for that object id. Here's what I'm imagining the code to look like:
Since I'm not doing an actual mutation I would assume I should use a
useQuery. However refetch doesn't allow me to imperatively pass in a param when I want to call the fetch. So doing a mutate makes more sense in my brain, but I feel like that isn't correct either.4 Replies
eastern-cyan•3y ago
Hi 👋
A query would be correct here by the sounds of things. You'd want to set some state variable (the ID) that you use as a part of the query key and enable the query when there's a valid ID. This allows you to control when the query runs. Refetch simply refetches the current query - calling refetch with different arguments is such a common question and the answer is almost always to change the query key.
Hopefully this helps 🙂
rising-crimsonOP•3y ago
Makes perfect sense. Thanks!
eastern-cyan•3y ago
No worries :reactquery:
foreign-sapphire•3y ago
This is a mission for : https://tkdodo.eu/blog/react-query-fa-qs#how-can-i-pass-parameters-to-refetch 😉
React Query FAQs
Answering the most frequently asked React Query questions