T
TanStack•3y ago
rising-crimson

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:
const Component = () => {

const { data } = // useQuery or useMutation?

// Makes id from notification available
onNotificationReceivedEffect(id => {
loadObject(id) // method from react query
})

return (
<View>
<Text>{data.name}</Text>
</View>
)
}
const Component = () => {

const { data } = // useQuery or useMutation?

// Makes id from notification available
onNotificationReceivedEffect(id => {
loadObject(id) // method from react query
})

return (
<View>
<Text>{data.name}</Text>
</View>
)
}
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
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-crimson
rising-crimsonOP•3y ago
Makes perfect sense. Thanks!
eastern-cyan
eastern-cyan•3y ago
No worries :reactquery:
foreign-sapphire
foreign-sapphire•3y ago
React Query FAQs
Answering the most frequently asked React Query questions

Did you find this page helpful?