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>
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
