Is it considered bad practice to use a GET request with useMutation?
Hi everyone, I’m wondering if it’s okay to use a GET request with useMutation.
Here’s my situation: I need to check whether a specific version exists when the user enters a version name and clicks a button. To do this, I’m thinking of reusing the existing API that fetches the list of versions.
Would using useMutation for this GET request be considered bad practice?
10 Replies
extended-salmon•2mo ago
It’s not “wrong” to use a GET for a mutation but it’s uncommon and not widely accepted. It sounds like what you’re after is simply a disabled query. This also gives you the benefit of the result being in the
queryCache
https://tanstack.com/query/latest/docs/framework/react/guides/disabling-queriesDisabling/Pausing Queries | TanStack Query React Docs
If you ever want to disable a query from automatically running, you can use the enabled = false option. The enabled option also accepts a callback that returns a boolean. When enabled is false: If the...
rival-blackOP•2mo ago
It’s because I need the result of getVersions inside a function, and based on that result, I’ll determine what to do next. So in this case, I don’t think the enabled option helps, since the check is related to an event which triggered by a user
extended-salmon•2mo ago
That’s what
const version = await refetch()
would berival-blackOP•2mo ago
ahh I see. I'll try it
May I ask how can I pass
search
to refetch
extended-salmon•2mo ago
React Query FAQs
Answering the most frequently asked React Query questions
rival-blackOP•2mo ago
As I mentioned before, I need to handle everything in an event. If I use state, I need to wait for the next life cycle, which does not help in my case.
afraid-scarlet•2mo ago
You can also use fetch (edit: I meant fetchQuery, sorry for not clarifying) if you havn't mounted the query before (since refetch won’t work if you havn't run it before). Normal fetch will essentially work identical to mutate, except the value is cached in the query cache and will use that if an identical parameter is provided.
extended-salmon•2mo ago
How about
fetchQuery
?
https://tanstack.com/query/latest/docs/reference/QueryClient#queryclientfetchqueryQueryClient | TanStack Query Docs
QueryClient The QueryClient can be used to interact with a cache: tsx import { QueryClient } from '@tanstack/react-query' const queryClient = new QueryClient({ defaultOptions: { queries: { staleTime:...
extended-salmon•2mo ago
All the goodness of RQ like cache, statuses, etc and it’ll happen in your one event lifecycle
rival-blackOP•2mo ago
fetchQuery
seems to work well in my case. Thanks everyone