Convex mutation inside tanstack/react query mutation

I want to do crazy browser push api stuff. For this I want to abstract a function inside a tanstack query mutation this tanstack mutation has to call the convex mutation. (it has to make a db write and a bunch of extra stuff) Is that possible with the convex mutation?
13 Replies
erquhart
erquhart8mo ago
Neither Tanstack Query or Convex care what you do with the result of a mutation, so it should work just fine.
FleetAdmiralJakob 🗕 🗗 🗙
but I to define to convex mutation inside the tanstack mutation ig so it's not just about the results it's about the defintion
erquhart
erquhart8mo ago
You mean calling useMutation()? The definition is backend so I'm guessing you're not referring to that
FleetAdmiralJakob 🗕 🗗 🗙
Mhmm, maybe I break it down to that:
const mutation = useMutation({
mutationFn: // Can I define the convex mutation here?
})
const mutation = useMutation({
mutationFn: // Can I define the convex mutation here?
})
erquhart
erquhart8mo ago
import { useMutation as useConvexMutation } from 'convex/react'
import { useMutation } from 'tanstack/query'

const convexMutation = useConvexMutation(api.my.func)
const mutation = useMutation({
mutationFn: async () => {
await convexMutation()
}
})
import { useMutation as useConvexMutation } from 'convex/react'
import { useMutation } from 'tanstack/query'

const convexMutation = useConvexMutation(api.my.func)
const mutation = useMutation({
mutationFn: async () => {
await convexMutation()
}
})
(obvs the hooks need to be inside of a hook or component)
FleetAdmiralJakob 🗕 🗗 🗙
ok, so I wrap the two hooks inside a hook sounds reasonable thank you
erquhart
erquhart8mo ago
For sure
FleetAdmiralJakob 🗕 🗗 🗙
❤️ You're the best so tried it. It's not working, but I think it's just the complexity of the functionality that I want to implement. If I have problems with the setup I will write it here.
erquhart
erquhart8mo ago
If you can share any code (and the expected vs actual behavior), happy to take a look
Michal Srb
Michal Srb8mo ago
Tiny bit simpler:
import { useConvex } from 'convex/react'
import { useMutation } from 'tanstack/query'

const convex = useConvex()
const mutation = useMutation({
mutationFn: async () =>
await convex.mutation(api.foo.bla)
})
import { useConvex } from 'convex/react'
import { useMutation } from 'tanstack/query'

const convex = useConvex()
const mutation = useMutation({
mutationFn: async () =>
await convex.mutation(api.foo.bla)
})
FleetAdmiralJakob 🗕 🗗 🗙
Never used useConvex. Does it has any other benifits besides that it is simpler?
jamwt
jamwt8mo ago
it just gives you a lower-level handle to the ConvexReactClient
Michal Srb
Michal Srb7mo ago
convex/react's useMutation gives you a memoized callback and optimistic updates, neither of which are needed in this example given you're using useMutation from tanstack/query.

Did you find this page helpful?