|
1 | 1 | --- |
2 | 2 | title: Mutation Hook |
3 | 3 | category: Data Fetching |
4 | | -layer: lib/api/ |
5 | | -composedWith: query-keys-factory |
| 4 | +layer: providers/ |
| 5 | +composedWith: mutation-options-factory, query-keys-factory |
6 | 6 | --- |
7 | 7 |
|
8 | 8 | ## Mutation Hook |
9 | 9 |
|
10 | | -Server write operations wrapped in `useMutation` with domain error translation and cache invalidation via `query-keys-factory`. Returns a `[handler, isPending]` tuple: the handler encapsulates the async call + error mapping. |
| 10 | +Server write hook composed from `mutation-options-factory`. Spreads the factory options and adds e.g. cache invalidation or custom error handling. Returns a `[handler, isPending]` tuple. Lives in `providers/` — the data access gateway for the feature slice. |
11 | 11 |
|
12 | 12 | ### Constraints |
13 | 13 |
|
14 | | -- Error classes are co-located with the hook — they're reusable across feature slices, so they live with the mutation definition. |
15 | | -- Keep the handler's error mapping exhaustive: catch API errors, translate to typed domain errors, fall back to `UnknownError`. Components should never see raw HTTP errors. |
16 | | -- Invalidation belongs here — the mutation knows what resource it wrote to, so it owns cache coherence via `query-keys-factory`. |
17 | | -- ALWAYS use `use` prefix in names — `useXxxMutation`, never `xxxMutation`. File: `use-xxx-mutation.ts`. |
| 14 | +- ALWAYS use `use` prefix — `useXxxMutation`, never `xxxMutation`. File: `use-xxx-mutation.ts` |
| 15 | +- Compose from a `mutation-options-factory` via spread |
| 16 | +- Invalidation belongs here — the hook knows what queries to invalidate via `query-keys-factory` |
| 17 | +- When the consumer needs to extend `onSuccess` (e.g., close a modal after mutation), spread and chain the factory's callbacks |
18 | 18 |
|
19 | 19 | ### Example |
20 | 20 |
|
21 | 21 | ```tsx |
| 22 | +// src/features/carts/providers/use-add-to-cart-mutation.ts |
22 | 23 | import { useMutation, useQueryClient } from "@tanstack/react-query"; |
23 | | -import { httpService } from "@/lib/http"; // project HTTP client |
24 | | -import { Logger } from "@/lib/logger"; |
25 | | -import { UnknownError } from "@/lib/types/unknown-error"; |
26 | | -import { cartQueryKeys } from "@/lib/api/carts/cart-query-keys"; // query-keys-factory |
| 24 | +import { addToCartMutationOptions } from "@/lib/api/carts/add-to-cart/add-to-cart-mutation"; |
| 25 | +import { cartQueryKeys } from "@/lib/api/carts/cart-query-keys"; |
27 | 26 |
|
28 | | -interface AddToCartPayload { |
29 | | - productId: number; |
30 | | - quantity?: number; |
31 | | -} |
32 | | - |
33 | | -interface AddToCartDto { |
34 | | - cartId: number; |
35 | | - payload: AddToCartPayload; |
36 | | -} |
37 | | - |
38 | | -export const useAddToCartMutation = () => { |
| 27 | +export const useAddToCartMutation = (cartId: number) => { |
39 | 28 | const queryClient = useQueryClient(); |
40 | 29 |
|
41 | | - const { mutateAsync, isPending } = useMutation<void, unknown, AddToCartDto>({ |
42 | | - mutationFn: (body) => |
43 | | - httpService.put<void, AddToCartPayload>(`carts/${body.cartId}`, { |
44 | | - productId: body.payload.productId, |
45 | | - quantity: body.payload.quantity, |
46 | | - }), |
47 | | - onSuccess: (_data, variables) => { |
| 30 | + const { mutateAsync, isPending } = useMutation({ |
| 31 | + ...addToCartMutationOptions, |
| 32 | + onSuccess: () => { |
48 | 33 | queryClient.invalidateQueries({ |
49 | | - queryKey: cartQueryKeys.detail(variables.cartId), |
| 34 | + queryKey: cartQueryKeys.detail(cartId), |
50 | 35 | }); |
51 | 36 | }, |
52 | 37 | }); |
53 | 38 |
|
54 | | - const handler = async (cartId: number, payload: AddToCartPayload) => { |
55 | | - try { |
56 | | - return await mutateAsync({ cartId, payload }); |
57 | | - } catch (e) { |
58 | | - Logger.error("Failed to add item to cart", e as Error); |
59 | | - |
60 | | - if (httpService.isError(e) && e.message === "Unknown product") { |
61 | | - throw new UnknownProductError(); |
62 | | - } |
63 | | - if (httpService.isError(e) && e.message === "Product not available") { |
64 | | - throw new ProductNotAvailableError(); |
65 | | - } |
66 | | - |
67 | | - throw new UnknownError(); |
68 | | - } |
| 39 | + const handler = async (payload: AddToCartPayload) => { |
| 40 | + return mutateAsync({ cartId, payload }); |
69 | 41 | }; |
70 | 42 |
|
71 | 43 | return [handler, isPending] as const; |
72 | 44 | }; |
| 45 | +``` |
73 | 46 |
|
74 | | -export class UnknownProductError extends Error { |
75 | | - constructor() { |
76 | | - super("Unknown product"); |
77 | | - this.name = "UnknownProductError"; |
78 | | - } |
79 | | -} |
| 47 | +### References |
80 | 48 |
|
81 | | -export class ProductNotAvailableError extends Error { |
82 | | - constructor() { |
83 | | - super("Product not available"); |
84 | | - this.name = "ProductNotAvailableError"; |
85 | | - } |
86 | | -} |
87 | | -``` |
| 49 | +- `rules/mutation-options-factory.md` — raw factory pattern in `lib/api/` |
| 50 | +- `rules/query-keys-factory.md` — cache key structure for invalidation |
0 commit comments