Web / TanStack Interview Questions
How do you pass variables to a mutation and use them across lifecycle callbacks?
The mutationFn, onMutate, onSuccess, onError, and onSettled callbacks all receive the mutation variables as their first argument. The exposed variables ref also holds the in-flight variables for use in the template.
<script setup lang="ts"> import { useMutation, useQueryClient } from "@tanstack/vue-query" const qc=useQueryClient() interface UpdateInput { id:number; name:string; email:string } const { mutate:updateUser, isPending, variables }=useMutation({ mutationFn: (input:UpdateInput)=> fetch(`/api/users/${input.id}`,{ method:"PUT", body:JSON.stringify(input), }).then(r=>r.json()), onSuccess: (data, vars)=>{ qc.setQueryData(["user",vars.id], data) // write response directly into cache toast.success(`Updated ${vars.name}`) }, onError: (err, vars)=>{ toast.error(`Failed to update ${vars.name}: ${err.message}`) }, }) </script> <template> <button @click="updateUser(form)" :disabled="isPending"> {{ isPending ? `Saving ${variables?.name}...` : "Save" }} </button> </template>
More Related questions...