TanStackIntermediate
Update Mutation — Edit Product
PUT/PATCH দিয়ে product edit এবং detail/list cache আপডেট — বাংলায়।
7টি অংশবাংলা ভাষায়
Edit-ও একই pattern — শুধু mutationFn-এ id আর নতুন values যায়। আমরা detail cache-ও আপডেট করব যেন পেজে edit-এর পর সঠিক ডেটা থাকে।
use-product-mutations.ts (add)ts
ts
export function useUpdateProduct() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: ({ id, input }: { id: string; input: CreateProductInput }) =>
updateProduct(id, input),
onSuccess: (data) => {
// list-গুলো ইনভালিড (table আপডেট)
queryClient.invalidateQueries({ queryKey: productKeys.lists() });
// edit করা product-এর detail cache-ও হালনাগাদ
queryClient.setQueryData(
productKeys.detail(data.id),
data
);
toast.success("Product আপডেট হয়েছে");
},
onError: (error) => toast.error(error.message),
});
}কেন setQueryData detail-এ
সংখ্যাগত দুই অপরে শুধু invalidateQueries করলে detail page আবার fetch করবে — দ্রুত তো ঠিকই, তবে ব্যবহারকারী যদি ঠিক edit-করা item-এ থাকেন, instant দেখানোর জন্য আমরা নিজে cache সেট করলাম। দুটোই জায়েজ।
Edit form-এ call
Dialog-এtsx
tsx
const updateProduct = useUpdateProduct();
function handleUpdate(values: CreateProductInput) {
updateProduct.mutate(
{ id: product.id, input: values },
{ onSuccess: () => onClose?.() }
);
}Partial update চাইলে
API পাশে PATCH support থাকলে input: Partial<CreateProductInput> ব্যবহার করা যায় — শুধু বদলানো fields-টিই পাঠানো হয়। PUT সম্পূর্ণ replace, PATCH আংশিক। আমরা PUT নেব (সব fields সম্পূর্ণ হিসেবে)।
শেষ প্যারায় নিজে practice করুন — কোড কপি করে নিজের এডিটরে চালিয়ে দেখুন।