| name | react-query-mutation-pattern |
| description | null |
Mutation Pattern
Category: react-query · Status: 🟢 Active
When to use
Khi tạo/sửa/xoá data server-state bằng useMutation.
Steps
- Tách mutationFn ra service layer, nhận biến đầu vào rõ kiểu.
- Trong
onSuccess gọi invalidateQueries đúng queryKey liên quan.
- Dùng
isPending để disable nút, hiển thị loading.
- Xử lý lỗi ở
onError (toast/message); không nuốt lỗi.
- Đóng gói vào hook
useXxxMutation để tái sử dụng.
Template
export function useCreatePost() {
const qc = useQueryClient();
return useMutation({
mutationFn: (input: CreatePostInput) => postApi.create(input),
onSuccess: () => qc.invalidateQueries({ queryKey: ['posts'] }),
onError: (e) => toast.error(getErrorMessage(e)),
});
}
Example
Good: invalidate sau success, isPending disable nút, onError toast.
Avoid: Không invalidate (UI stale), bỏ loading, nuốt lỗi im lặng.
Checklist