1 ---
2 tags:
3 - storefront
4 ---
5
6 import { Table, CodeTabs } from "docs-ui"
7
8 export const metadata = {
9 title: `Storefront Production Optimization Tips`,
10 }
11
12 # {metadata.title}
13
14 In this guide, you’ll find tips useful when optimizing a storefront for production.
15
16 ## Summary
17
18 When building a storefront, you want to ensure that it loads quickly and efficiently for your users. You can achieve this by implementing many optimizations, including:
19
20 1. [Implement appropriate rendering strategies](#choose-the-right-rendering-strategy).
21 2. [Use fetching libraries optimized for performance and caching like TanStack Query](#use-tanstack-query).
22 3. [Optimize queries to fetch only the necessary data](#optimize-fetched-data).
23 4. [Implement optimistic UI updates for cart operations](#implement-optimistic-ui-updates).
24
25 This guide explains how to implement these optimizations. You can follow it regardless of the frontend framework you use.
26
27 <Note>
28
29 There are other important optimizations like lazy-loading images, code-splitting, and using CDNs. These optimizations depend on the frontend framework you use and your setup. This guide focuses on Medusa-specific optimizations in your storefront.
30
31 </Note>
32
33 ---
34
35 ## Choose the Right Rendering Strategy
36
37 A rendering strategy defines how your frontend framework renders pages. The most common strategies are:
38
39 1. **Server-Side Rendering (SSR)**: Pages are rendered on the server for each request. Ideal for dynamic content that changes frequently.
40 2. **Static Site Generation (SSG)**: Pages are pre-rendered at build time. Best suited for content that doesn't change often.
41 3. **Incremental Static Regeneration (ISR)**: A hybrid approach where pages are pre-rendered at build time but can be updated at runtime. Perfect for content that changes occasionally.
42 4. **Client-Side Rendering (CSR)**: Pages are rendered in the browser using JavaScript. Optimal for highly interactive applications.
43
44 For your storefront, we recommend using different strategies for different pages:
45
46 <Table>
47 <Table.Header>
48 <Table.Row>
49 <Table.HeaderCell>
50 Page Type
51 </Table.HeaderCell>
52 <Table.HeaderCell>
53 Recommended Strategy
54 </Table.HeaderCell>
55 </Table.Row>
56 </Table.Header>
57 <Table.Body>
58 <Table.Row>
59 <Table.Cell>
60 Homepage
61 </Table.Cell>
62 <Table.Cell>
63 SSG above the fold, CSR below the fold. For example, render the hero section at build time and load product recommendations client-side.
64 </Table.Cell>
65 </Table.Row>
66 <Table.Row>
67 <Table.Cell>
68 Product Listing Page (PLP)
69 </Table.Cell>
70 <Table.Cell>
71 ISR or CSR.
72 </Table.Cell>
73 </Table.Row>
74 <Table.Row>
75 <Table.Cell>
76 Product Detail Page (PDP)
77 </Table.Cell>
78 <Table.Cell>
79 SSG for product content that doesn't change often, such as descriptions and images. Use CSR for dynamic content like stock availability and prices.
80 </Table.Cell>
81 </Table.Row>
82 <Table.Row>
83 <Table.Cell>
84 Cart and Checkout Pages
85 </Table.Cell>
86 <Table.Cell>
87 CSR.
88 </Table.Cell>
89 </Table.Row>
90 <Table.Row>
91 <Table.Cell>
92 Blog or Content Pages (About Us, Privacy Policy, etc...)
93 </Table.Cell>
94 <Table.Cell>
95 SSG or ISR.
96 </Table.Cell>
97 </Table.Row>
98 <Table.Row>
99 <Table.Cell>
100 User Account Pages
101 </Table.Cell>
102 <Table.Cell>
103 CSR.
104 </Table.Cell>
105 </Table.Row>
106 </Table.Body>
107 </Table>
108
109 How you implement these strategies depends on the frontend framework you use. Refer to the documentation of your framework for guidance.
110
111 ---
112
113 ## Use TanStack Query
114
115 When fetching data from your Medusa backend, consider using a fetching library optimized for performance and caching. There are many options available, but one of the most popular is [TanStack Query](https://tanstack.com/query/latest).
116
117 TanStack Query is a powerful data-fetching library that provides features like caching, background updates, and optimistic updates.
118
119 By using TanStack Query, you can significantly improve your storefront's performance by reducing the number of network requests and ensuring that your UI is always up-to-date.
120
121 Learn how to get started with TanStack Query in their [official documentation](https://tanstack.com/query/latest/docs/framework/react/installation). Their documentation also has guidance on advanced usage and best practices.
122
123 ### Stale Time Configuration
124
125 When configuring TanStack Query, you can set the `staleTime` option to control how long data is considered fresh. However, avoid setting `staleTime` for highly dynamic data like product prices and stock levels.
126
127 Set the `staleTime` globally, then override it to `0` for specific queries that fetch dynamic data.
128
129 For example:
130
131 ```ts
132 // queryClient.ts
133 import { QueryClient } from "@tanstack/react-query"
134
135 const queryClient = new QueryClient({
136 defaultOptions: {
137 queries: {
138 staleTime: 1000 * 60 * 5, // 5 minutes
139 },
140 },
141 })
142
143 export default queryClient
144
145 // product.ts
146 // Used in components that are children of QueryClientProvider
147 import { useQuery } from "@tanstack/react-query"
148 import { sdk } from "../lib/sdk"
149
150 export const useProduct = (id: string) => {
151 return useQuery(["product", id], async () => {
152 const response = await sdk.store.products.retrieve(id)
153 return response.data
154 })
155 }
156
157 export const useProductPrice = (id: string) => {
158 return useQuery(
159 ["product-price", id],
160 async () => {
161 const response = await sdk.store.products.retrieve(id, {
162 fields: "*variants.calculated_price",
163 })
164 return response.data.variants[0].price
165 },
166 {
167 staleTime: 0, // Always fetch fresh data
168 }
169 )
170 }
171 ```
172
173 ### Invalidate Queries
174
175 When performing mutations that change cached data, invalidate the relevant queries to ensure that the UI reflects the latest data.
176
177 For example, when adding an item to the cart, you should invalidate the cart query:
178
179 ```ts
180 import { useMutation, useQueryClient } from "@tanstack/react-query"
181 import { sdk } from "../lib/sdk"
182
183 export const useAddToCart = () => {
184 const queryClient = useQueryClient()
185
186 return useMutation(
187 async (item) => {
188 await sdk.store.cart.createLineItem("cart_id", item)
189 },
190 {
191 onSuccess: () => {
192 queryClient.invalidateQueries(["cart"])
193 },
194 }
195 )
196 }
197 ```
198
199 ---
200
201 ## Optimize Fetched Data
202
203 When fetching data from your Medusa backend, optimize your queries to fetch only the necessary data in the context of a component or page. This reduces the response size and time, improving your storefront's performance.
204
205 Medusa's API routes accept a `fields` parameter that allows you to specify which fields and relations to include in the response.
206
207 For example, if you only need the product's `id`, `title`, and `variants.calculated_price`, you can specify this in the `fields` parameter:
208
209 ```ts
210 const response = await sdk.store.products.retrieve("product_id", {
211 fields: "*variants.calculated_price, id, title",
212 })
213 ```
214
215 This query will return only the specified fields, reducing the response size and improving performance.
216
217 If you're using TanStack Query, make sure to include the `fields` parameter in the query key to ensure that different field selections are cached separately:
218
219 ```ts
220 const useProduct = (id: string, fields?: string) => {
221 return useQuery({
222 queryKey: ["product", id, fields],
223 queryFn: async () => {
224 const response = await sdk.store.products.retrieve(id, { fields })
225 return response.data
226 },
227 })
228 }
229 ```
230
231 Learn more about the `fields` parameter in the [Store API reference](!api!/store/select-fields-and-relations).
232
233 Each Store API route restricts the fields that you can request through an allowed-fields list. If you request a field that the route doesn't allow, Medusa omits it from the response without returning an error.
234
235 To allow extra fields, such as a custom relation, override the route's allowed fields as explained in the [Allowed Fields](!docs!/learn/fundamentals/api-routes/allowed-fields) documentation.
236
237 ---
238
239 ## Implement Optimistic UI Updates
240
241 When performing mutations that may take some time, you can implement optimistic UI updates to provide a better user experience. This means updating the UI immediately, assuming the mutation will succeed, then rolling back if it fails.
242
243 For example, if you're using TanStack Query, you can implement the following optimistic cart-update utilities and then use them in cart mutations:
244
245 <Note forceMultiline>
246
247 The following code snippets are not complete implementations. They are simplified for clarity. They assume that:
248
249 - You defined separate cart data functions that use the [JS SDK](../../js-sdk/page.mdx) to call the Medusa backend.
250 - You have a `query-keys.ts` utility that defines consistent query keys for TanStack Query.
251
252 You can make changes as needed based on your implementation.
253
254 </Note>
255
256 <CodeTabs>
257 <CodeTab label="optimistic-cart.ts" value="optimistic-cart.ts">
258
259 ```ts title="optimistic-cart.ts" collapsibleLines="60-383" expandButtonLabel="Show all code"
260 import { HttpTypes } from "@medusajs/types"
261 import { QueryClient } from "@tanstack/react-query"
262 import { queryKeys } from "@/lib/utils/common/query-keys"
263
264 /**
265 * Utility functions for optimistic cart updates
266 */
267
268 export interface OptimisticCartItem {
269 id: string;
270 variant_id: string;
271 quantity: number;
272 title: string;
273 thumbnail?: string | null;
274 product_title?: string;
275 variant_title?: string;
276 product?: {
277 id: string;
278 title: string;
279 };
280 variant?: {
281 id: string;
282 title: string;
283 };
284 unit_price: number;
285 total: number;
286 isOptimistic?: boolean;
287 }
288
289 export interface OptimisticCart extends HttpTypes.StoreCart {
290 isOptimistic?: boolean;
291 }
292
293 /**
294 * Creates an optimistic cart item for immediate UI updates during add to cart operations.
295 * Generates a temporary item with calculated pricing before the server response.
296 *
297 * @param variant - The product variant being added to cart
298 * @param product - The product object containing title and thumbnail
299 * @param quantity - The quantity to add (defaults to 1)
300 * @returns Optimistic cart item with temporary ID and calculated totals
301 *
302 * @example
303 * ```typescript
304 * const optimisticItem = createOptimisticCartItem(variant, product, 2);
305 * // Returns item with temporary ID and calculated price for immediate UI update
306 * ```
307 */
308 export const createOptimisticCartItem = (
309 variant: HttpTypes.StoreProductVariant,
310 product: HttpTypes.StoreProduct,
311 quantity: number = 1
312 ): OptimisticCartItem => {
313 const unitPrice = variant.calculated_price?.calculated_amount || 0
314
315 return {
316 id: `optimistic-${variant.id}-${Date.now()}`, // Temporary ID
317 variant_id: variant.id,
318 quantity,
319 title: product.title,
320 thumbnail: product.thumbnail,
321 product: {
322 id: product.id,
323 title: product.title,
324 },
325 product_title: product.title,
326 variant: {
327 id: variant.id,
328 title: variant.title || "Default Variant",
329 },
330 variant_title: variant.title || "Default Variant",
331 unit_price: unitPrice,
332 total: unitPrice * quantity,
333 isOptimistic: true,
334 }
335 }
336
337 /**
338 * Adds an item to the cart optimistically by updating the query cache immediately.
339 * This provides instant UI feedback while the actual API call is in progress.
340 *
341 * @param queryClient - TanStack Query client for cache management
342 * @param newItem - The optimistic cart item to add
343 * @param fields - Optional fields parameter for query key
344 * @returns Updated cart object or null if no current cart exists
345 *
346 * @example
347 * ```typescript
348 * const updatedCart = addItemOptimistically(queryClient, optimisticItem);
349 * if (updatedCart) {
350 * // UI immediately shows the new item
351 * // Real API call happens in background
352 * }
353 * ```
354 */
355 export const addItemOptimistically = (
356 queryClient: QueryClient,
357 newItem: OptimisticCartItem,
358 optimisticCart?: OptimisticCart,
359 fields?: string
360 ): HttpTypes.StoreCart | null => {
361 const currentCart = optimisticCart || queryClient.getQueryData<HttpTypes.StoreCart | null>(
362 queryKeys.cart.current(fields)
363 )
364
365 if (!currentCart) {
366 // If no cart exists, we can't add optimistically
367 // The mutation will handle creating a new cart
368 return null
369 }
370
371 // Check if item already exists in cart
372 const existingItemIndex = currentCart.items?.findIndex(
373 (item) => item.variant_id === newItem.variant_id
374 )
375
376 let updatedItems: HttpTypes.StoreCartLineItem[]
377
378 if (existingItemIndex !== undefined && existingItemIndex >= 0) {
379 // Update existing item quantity
380 updatedItems = [...(currentCart.items || [])]
381 const existingItem = updatedItems[existingItemIndex]
382 updatedItems[existingItemIndex] = {
383 ...existingItem,
384 quantity: existingItem.quantity + newItem.quantity,
385 total: (existingItem.unit_price || 0) * (existingItem.quantity + newItem.quantity),
386 }
387 } else {
388 // Add new item - cast to StoreCartLineItem for compatibility
389 const optimisticLineItem = {
390 ...newItem,
391 cart_id: currentCart.id,
392 cart: currentCart,
393 item_total: newItem.total,
394 item_subtotal: newItem.total,
395 item_tax_total: 0,
396 original_total: newItem.total,
397 original_tax_total: 0,
398 original_subtotal: newItem.total,
399 discount_total: 0,
400 discount_tax_total: 0,
401 gift_card_total: 0,
402 subtotal: newItem.total,
403 tax_total: 0,
404 total: newItem.total,
405 created_at: new Date(),
406 updated_at: new Date(),
407 metadata: {},
408 adjustments: [],
409 tax_lines: [],
410 unit_tax_amount: 0,
411 requires_shipping: true,
412 is_discountable: true,
413 is_tax_inclusive: false,
414 } as HttpTypes.StoreCartLineItem
415
416 updatedItems = [...(currentCart.items || []), optimisticLineItem]
417 }
418
419 const newItemSubtotal = updatedItems.reduce((sum, item) => sum + (item.total || 0), 0)
420
421 const newOptimisticCart: OptimisticCart = {
422 ...currentCart,
423 items: updatedItems,
424 item_subtotal: newItemSubtotal,
425 isOptimistic: true,
426 }
427
428 // Update the cache optimistically
429 queryClient.setQueryData(queryKeys.cart.current(fields), newOptimisticCart)
430
431 return newOptimisticCart
432 }
433
434 /**
435 * Updates a cart line item quantity optimistically in the query cache.
436 * Provides immediate UI feedback for quantity changes.
437 *
438 * @param queryClient - TanStack Query client for cache management
439 * @param lineId - The ID of the line item to update
440 * @param quantity - The new quantity for the line item
441 * @param fields - Optional fields parameter for query key
442 * @returns Updated cart object or null if no current cart exists
443 *
444 * @example
445 * ```typescript
446 * const updatedCart = updateLineItemOptimistically(queryClient, "line_123", 3);
447 * if (updatedCart) {
448 * // UI immediately shows updated quantity and totals
449 * }
450 * ```
451 */
452 export const updateLineItemOptimistically = (
453 queryClient: QueryClient,
454 lineId: string,
455 quantity: number,
456 fields?: string
457 ): HttpTypes.StoreCart | null => {
458 const currentCart = queryClient.getQueryData<HttpTypes.StoreCart | null>(
459 queryKeys.cart.current(fields)
460 )
461
462 if (!currentCart) {
463 return null
464 }
465
466 const updatedItems = (currentCart.items || []).map((item) => {
467 if (item.id === lineId) {
468 return {
469 ...item,
470 quantity,
471 total: (item.unit_price || 0) * quantity,
472 original_total: (item.unit_price || 0) * quantity,
473 }
474 }
475 return item
476 })
477
478 const optimisticCart: OptimisticCart = {
479 ...currentCart,
480 items: updatedItems,
481 item_subtotal: updatedItems.reduce((sum, item) => sum + (item.total || 0), 0),
482 isOptimistic: true,
483 }
484
485 queryClient.setQueryData(queryKeys.cart.current(fields), optimisticCart)
486
487 return optimisticCart
488 }
489
490 /**
491 * Removes a cart line item optimistically from the query cache.
492 * Provides immediate UI feedback for item removal.
493 *
494 * @param queryClient - TanStack Query client for cache management
495 * @param lineId - The ID of the line item to remove
496 * @param fields - Optional fields parameter for query key
497 * @returns Updated cart object or null if no current cart exists
498 *
499 * @example
500 * ```typescript
501 * const updatedCart = removeLineItemOptimistically(queryClient, "line_123");
502 * if (updatedCart) {
503 * // UI immediately shows item removed and updated totals
504 * }
505 * ```
506 */
507 export const removeLineItemOptimistically = (
508 queryClient: QueryClient,
509 lineId: string,
510 fields?: string
511 ): HttpTypes.StoreCart | null => {
512 const currentCart = queryClient.getQueryData<HttpTypes.StoreCart | null>(
513 queryKeys.cart.current(fields)
514 )
515
516 if (!currentCart) {
517 return null
518 }
519
520 const updatedItems = (currentCart.items || []).filter((item) => item.id !== lineId)
521
522 const optimisticCart: OptimisticCart = {
523 ...currentCart,
524 items: updatedItems,
525 item_subtotal: updatedItems.reduce((sum, item) => sum + (item.total || 0), 0),
526 isOptimistic: true,
527 }
528
529 queryClient.setQueryData(queryKeys.cart.current(fields), optimisticCart)
530
531 return optimisticCart
532 }
533
534 /**
535 * Rolls back optimistic cart changes when an API call fails.
536 * Restores the cart to its previous state before the optimistic update.
537 *
538 * @param queryClient - TanStack Query client for cache management
539 * @param previousCart - The cart state to restore to
540 * @param fields - Optional fields parameter for query key
541 *
542 * @example
543 * ```typescript
544 * try {
545 * await addToCart(variant);
546 * } catch (error) {
547 * // Rollback optimistic changes on error
548 * rollbackOptimisticCart(queryClient, previousCart);
549 * showErrorMessage("Failed to add item to cart");
550 * }
551 * ```
552 */
553 export const rollbackOptimisticCart = (
554 queryClient: QueryClient,
555 previousCart: HttpTypes.StoreCart | null,
556 fields?: string
557 ) => {
558 queryClient.setQueryData(queryKeys.cart.current(fields), previousCart)
559 }
560
561 /**
562 * Creates an optimistic cart for immediate UI updates during cart creation operations.
563 * Generates a temporary cart with basic structure before the server response.
564 *
565 * @param region_id - The region ID for the cart
566 * @param fields - Optional fields parameter for query key
567 * @returns Optimistic cart with temporary ID and basic structure
568 *
569 * @example
570 * ```typescript
571 * const optimisticCart = createOptimisticCart('reg_us');
572 * // Returns cart with temporary ID for immediate UI update
573 * ```
574 */
575 export const createOptimisticCart = (region: HttpTypes.StoreRegion): OptimisticCart => {
576 const tempId = `optimistic-cart-${Date.now()}`
577
578 return {
579 id: tempId,
580 region_id: region.id,
581 items: [],
582 item_subtotal: 0,
583 item_tax_total: 0,
584 item_total: 0,
585 original_item_total: 0,
586 original_item_tax_total: 0,
587 original_item_subtotal: 0,
588 original_total: 0,
589 original_tax_total: 0,
590 original_subtotal: 0,
591 subtotal: 0,
592 tax_total: 0,
593 total: 0,
594 discount_total: 0,
595 discount_tax_total: 0,
596 gift_card_total: 0,
597 gift_card_tax_total: 0,
598 shipping_total: 0,
599 shipping_tax_total: 0,
600 shipping_subtotal: 0,
601 original_shipping_total: 0,
602 original_shipping_subtotal: 0,
603 original_shipping_tax_total: 0,
604 shipping_address: undefined,
605 billing_address: undefined,
606 shipping_methods: [],
607 payment_collection: undefined,
608 region: undefined,
609 customer_id: undefined,
610 sales_channel_id: undefined,
611 promotions: [],
612 currency_code: region.currency_code,
613 metadata: {},
614 created_at: new Date(),
615 updated_at: new Date(),
616 isOptimistic: true,
617 }
618 }
619
620 /**
621 * Gets the current cart state from the query cache.
622 * First tries to get the cart with specific fields, then falls back to any cart query.
623 *
624 * @param queryClient - TanStack Query client for cache management
625 * @param fields - Optional fields parameter for query key
626 * @returns Current cart object or null if no cart found in cache
627 *
628 * @example
629 * ```typescript
630 * const currentCart = getCurrentCart(queryClient);
631 * if (currentCart) {
632 * // Use current cart state
633 * console.log(`Cart has ${currentCart.items?.length} items`);
634 * }
635 * ```
636 */
637 export const getCurrentCart = (queryClient: QueryClient, fields?: string): HttpTypes.StoreCart | null => {
638 return queryClient.getQueryData<HttpTypes.StoreCart | null>(queryKeys.cart.current(fields)) ||
639 queryClient.getQueriesData<HttpTypes.StoreCart | null>({
640 predicate: queryKeys.cart.predicate,
641 })[0]?.[1] || null
642 }
643 ```
644
645 </CodeTab>
646 <CodeTab label="use-cart.ts" value="use-cart.ts">
647
648 ```ts title="use-cart.ts" collapsibleLines="60-567" expandButtonLabel="Show all code"
649 import {
650 addToCart,
651 applyPromoCode,
652 createCart,
653 deleteLineItem,
654 removePromoCode,
655 retrieveCart,
656 updateCart,
657 updateLineItem,
658 } from "@/lib/data/cart"
659 import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"
660 import { queryKeys } from "@/lib/utils/common/query-keys"
661 import {
662 addItemOptimistically,
663 createOptimisticCartItem,
664 getCurrentCart,
665 rollbackOptimisticCart,
666 updateLineItemOptimistically,
667 removeLineItemOptimistically,
668 createOptimisticCart,
669 } from "@/lib/utils/cart/optimistic-cart"
670 import { HttpTypes } from "@medusajs/types"
671
672 /**
673 * React hook to fetch the current cart with optimistic updates and caching.
674 * Uses Tanstack Query with no stale time to ensure fresh data.
675 *
676 * @param fields - Optional fields to include in the cart response
677 * @returns Tanstack Query result object with cart data, loading, and error states
678 *
679 * @example
680 * ```typescript
681 * // Basic usage
682 * const { data: cart, isLoading, error } = useCart();
683 *
684 * // With specific fields
685 * const { data: cart } = useCart({
686 * fields: '*items, *items.variant, *items.product, shipping_methods'
687 * });
688 *
689 * // In a component
690 * function CartSummary() {
691 * const { data: cart, isLoading } = useCart();
692 *
693 * if (isLoading) return <div>Loading cart...</div>;
694 * if (!cart) return <div>No cart found</div>;
695 *
696 * return (
697 * <div>
698 * <h2>Cart ({cart.items.length} items)</h2>
699 * <p>Total: {cart.total}</p>
700 * </div>
701 * );
702 * }
703 * ```
704 */
705 export const useCart = ({ fields }: { fields?: string } = {}) => {
706 return useQuery({
707 queryKey: queryKeys.cart.current(fields),
708 queryFn: () => retrieveCart({ fields }),
709 staleTime: 0,
710 })
711 }
712
713 /**
714 * React hook to update the cart with automatic cache invalidation.
715 * Uses Tanstack Query's useMutation for handling cart updates.
716 *
717 * @returns Tanstack Query mutation object with mutate function and state
718 *
719 * @example
720 * ```typescript
721 * // Basic usage
722 * const updateCartMutation = useUpdateCart();
723 *
724 * // Usage in component
725 * function UpdateCartButton() {
726 * const updateCartMutation = useUpdateCart();
727 *
728 * const handleUpdateCart = () => {
729 * updateCartMutation.mutate({
730 * region_id: 'reg_us'
731 * }, {
732 * onSuccess: (cart) => {
733 * console.log('Cart updated:', cart);
734 * },
735 * onError: (error) => {
736 * console.error('Failed to update cart:', error);
737 * }
738 * });
739 * };
740 *
741 * return (
742 * <button
743 * onClick={handleUpdateCart}
744 * disabled={updateCartMutation.isPending}
745 * >
746 * {updateCartMutation.isPending ? 'Updating...' : 'Update Cart'}
747 * </button>
748 * );
749 * }
750 * ```
751 */
752 export const useUpdateCart = () => {
753 const queryClient = useQueryClient()
754 return useMutation({
755 mutationFn: updateCart,
756 onSuccess: () => {
757 queryClient.invalidateQueries({ predicate: queryKeys.cart.predicate })
758 },
759 })
760 }
761
762 /**
763 * React hook to create a new cart with automatic cache invalidation.
764 * Uses Tanstack Query's useMutation for handling cart creation.
765 *
766 * @returns Tanstack Query mutation object with mutate function and state
767 *
768 * @example
769 * ```typescript
770 * // Basic usage
771 * const createCartMutation = useCreateCart();
772 *
773 * // Usage in component
774 * function CreateCartButton() {
775 * const createCartMutation = useCreateCart();
776 *
777 * const handleCreateCart = () => {
778 * createCartMutation.mutate(
779 * { region_id: 'reg_us' },
780 * {
781 * onSuccess: (cart) => {
782 * console.log('Cart created:', cart.id);
783 * // Redirect to cart page
784 * },
785 * onError: (error) => {
786 * console.error('Failed to create cart:', error);
787 * }
788 * }
789 * );
790 * };
791 *
792 * return (
793 * <button
794 * onClick={handleCreateCart}
795 * disabled={createCartMutation.isPending}
796 * >
797 * {createCartMutation.isPending ? 'Creating...' : 'Create Cart'}
798 * </button>
799 * );
800 * }
801 * ```
802 */
803 export const useCreateCart = () => {
804 const queryClient = useQueryClient()
805
806 return useMutation({
807 mutationFn: createCart,
808 onSuccess: () => {
809 queryClient.invalidateQueries({ predicate: queryKeys.cart.predicate })
810 },
811 })
812 }
813
814 /**
815 * React hook to add items to cart with optimistic updates.
816 * Provides immediate UI feedback while the request is in progress.
817 *
818 * @param fields - Optional fields to include in the cart response
819 * @returns Tanstack Query mutation object with mutate function and state
820 *
821 * @example
822 * ```typescript
823 * // Basic usage
824 * const addToCartMutation = useAddToCart();
825 *
826 * // Usage in component
827 * function AddToCartButton({ variant, product }) {
828 * const addToCartMutation = useAddToCart();
829 *
830 * const handleAddToCart = () => {
831 * addToCartMutation.mutate({
832 * variant_id: variant.id,
833 * quantity: 1,
834 * country_code: 'us',
835 * product,
836 * variant
837 * }, {
838 * onSuccess: (cart) => {
839 * console.log('Added to cart:', cart);
840 * // Show success message
841 * },
842 * onError: (error) => {
843 * console.error('Failed to add to cart:', error);
844 * // Show error message
845 * }
846 * });
847 * };
848 *
849 * return (
850 * <button
851 * onClick={handleAddToCart}
852 * disabled={addToCartMutation.isPending}
853 * >
854 * {addToCartMutation.isPending ? 'Adding...' : 'Add to Cart'}
855 * </button>
856 * );
857 * }
858 *
859 * // With custom fields
860 * const addToCartWithFields = useAddToCart({
861 * fields: '*items, *items.variant, shipping_methods'
862 * });
863 * ```
864 */
865 export const useAddToCart = ({ fields }: { fields?: string } = {}) => {
866 const queryClient = useQueryClient()
867
868 return useMutation({
869 mutationFn: (variables) => addToCart({ ...variables, fields }),
870 onMutate: async (variables: {
871 variant_id: string;
872 quantity: number;
873 country_code: string;
874 product?: HttpTypes.StoreProduct;
875 variant?: HttpTypes.StoreProductVariant;
876 region?: HttpTypes.StoreRegion;
877 }) => {
878 // Cancel any outgoing refetches
879 await queryClient.cancelQueries({ predicate: queryKeys.cart.predicate })
880
881 // Snapshot the previous value
882 let previousCart = getCurrentCart(queryClient, fields)
883 let didCartExist = true
884
885 if (!previousCart && variables.region) {
886 previousCart = createOptimisticCart(variables.region)
887 didCartExist = false
888 }
889
890 // If we have a cart and product/variant data, we can add optimistically
891 if (previousCart && variables.product !== undefined && variables.variant !== undefined) {
892 const optimisticItem = createOptimisticCartItem(
893 variables.variant,
894 variables.product,
895 variables.quantity
896 )
897
898 addItemOptimistically(queryClient, optimisticItem, previousCart, fields)
899 }
900
901 // Return a context object with the snapshotted value
902 return { previousCart: didCartExist ? previousCart : undefined }
903 },
904 onError: (err, variables, context) => {
905 // If the mutation fails, use the context returned from onMutate to roll back
906 if (context?.previousCart) {
907 rollbackOptimisticCart(queryClient, context.previousCart, fields)
908 }
909 },
910 onSettled: (data) => {
911 // Always refetch after error or success to ensure we have the latest data
912 queryClient.invalidateQueries({ predicate:
913 (query) => queryKeys.cart.predicate(query, fields && data ? [fields] : undefined),
914 })
915 if (data) {
916 queryClient.setQueryData(queryKeys.cart.current(fields), data)
917 }
918 },
919 })
920 }
921
922 /**
923 * React hook to update line item quantities with optimistic updates.
924 * Provides immediate UI feedback while the request is in progress.
925 *
926 * @param fields - Optional fields to include in the cart response
927 * @returns Tanstack Query mutation object with mutate function and state
928 *
929 * @example
930 * ```typescript
931 * // Basic usage
932 * const updateLineItemMutation = useUpdateLineItem();
933 *
934 * // Usage in component
935 * function QuantitySelector({ lineItem }) {
936 * const updateLineItemMutation = useUpdateLineItem();
937 *
938 * const handleQuantityChange = (newQuantity: number) => {
939 * updateLineItemMutation.mutate({
940 * line_id: lineItem.id,
941 * quantity: newQuantity
942 * }, {
943 * onSuccess: (cart) => {
944 * console.log('Quantity updated:', cart);
945 * },
946 * onError: (error) => {
947 * console.error('Failed to update quantity:', error);
948 * }
949 * });
950 * };
951 *
952 * return (
953 * <select
954 * value={lineItem.quantity}
955 * onChange={(e) => handleQuantityChange(Number(e.target.value))}
956 * disabled={updateLineItemMutation.isPending}
957 * >
958 * {[1, 2, 3, 4, 5].map(num => (
959 * <option key={num} value={num}>{num}</option>
960 * ))}
961 * </select>
962 * );
963 * }
964 * ```
965 */
966 export const useUpdateLineItem = ({ fields }: { fields?: string } = {}) => {
967 const queryClient = useQueryClient()
968
969 return useMutation({
970 mutationFn: (variables: {
971 line_id: string;
972 quantity: number;
973 }) => updateLineItem({ ...variables, fields }),
974 onMutate: async (variables) => {
975 // Cancel any outgoing refetches
976 await queryClient.cancelQueries({
977 predicate: (query) => queryKeys.cart.predicate(query, fields ? [fields] : undefined),
978 })
979
980 // Snapshot the previous value
981 const previousCart = getCurrentCart(queryClient, fields)
982
983 // Update optimistically
984 if (previousCart) {
985 updateLineItemOptimistically(queryClient, variables.line_id, variables.quantity, fields)
986 }
987
988 // Return a context object with the snapshotted value
989 return { previousCart }
990 },
991 onError: (err, variables, context) => {
992 // If the mutation fails, use the context returned from onMutate to roll back
993 if (context?.previousCart) {
994 rollbackOptimisticCart(queryClient, context.previousCart, fields)
995 }
996 },
997 onSettled: (data) => {
998 // Always refetch after error or success to ensure we have the latest data
999 queryClient.invalidateQueries({ predicate:
1000 (query) => queryKeys.cart.predicate(query, fields && data ? [fields] : undefined),
1001 })
1002 if (data) {
1003 queryClient.setQueryData(queryKeys.cart.current(fields), data)
1004 }
1005 },
1006 })
1007 }
1008
1009 /**
1010 * React hook to delete line items with optimistic updates.
1011 * Provides immediate UI feedback while the request is in progress.
1012 *
1013 * @param fields - Optional fields to include in the cart response
1014 * @returns Tanstack Query mutation object with mutate function and state
1015 *
1016 * @example
1017 * ```typescript
1018 * // Basic usage
1019 * const deleteLineItemMutation = useDeleteLineItem();
1020 *
1021 * // Usage in component
1022 * function CartItem({ lineItem }) {
1023 * const deleteLineItemMutation = useDeleteLineItem();
1024 *
1025 * const handleRemoveItem = () => {
1026 * deleteLineItemMutation.mutate({
1027 * line_id: lineItem.id
1028 * }, {
1029 * onSuccess: (cart) => {
1030 * console.log('Item removed:', cart);
1031 * // Show success message
1032 * },
1033 * onError: (error) => {
1034 * console.error('Failed to remove item:', error);
1035 * // Show error message
1036 * }
1037 * });
1038 * };
1039 *
1040 * return (
1041 * <div>
1042 * <span>{lineItem.title}</span>
1043 * <button
1044 * onClick={handleRemoveItem}
1045 * disabled={deleteLineItemMutation.isPending}
1046 * >
1047 * {deleteLineItemMutation.isPending ? 'Removing...' : 'Remove'}
1048 * </button>
1049 * </div>
1050 * );
1051 * }
1052 * ```
1053 */
1054 export const useDeleteLineItem = ({ fields }: { fields?: string } = {}) => {
1055 const queryClient = useQueryClient()
1056
1057 return useMutation({
1058 mutationFn: (variables: {
1059 line_id: string;
1060 }) => deleteLineItem({ ...variables, fields }),
1061 onMutate: async (variables) => {
1062 // Cancel any outgoing refetches
1063 await queryClient.cancelQueries({ predicate:
1064 (query) => queryKeys.cart.predicate(query, fields ? [fields] : undefined),
1065 })
1066
1067 // Snapshot the previous value
1068 const previousCart = getCurrentCart(queryClient, fields)
1069
1070 // Remove optimistically
1071 if (previousCart) {
1072 removeLineItemOptimistically(queryClient, variables.line_id, fields)
1073 }
1074
1075 // Return a context object with the snapshotted value
1076 return { previousCart }
1077 },
1078 onError: (err, variables, context) => {
1079 // If the mutation fails, use the context returned from onMutate to roll back
1080 if (context?.previousCart) {
1081 rollbackOptimisticCart(queryClient, context.previousCart, fields)
1082 }
1083 },
1084 onSettled: (data) => {
1085 // Always refetch after error or success to ensure we have the latest data
1086 queryClient.invalidateQueries({ predicate:
1087 (query) => queryKeys.cart.predicate(query, fields && data ? [fields] : undefined),
1088 })
1089 if (data) {
1090 queryClient.setQueryData(queryKeys.cart.current(fields), data)
1091 }
1092 },
1093 })
1094 }
1095
1096 /**
1097 * React hook to apply promotion codes to the cart.
1098 * Automatically invalidates cart cache on success.
1099 *
1100 * @returns Tanstack Query mutation object with mutate function and state
1101 *
1102 * @example
1103 * ```typescript
1104 * // Basic usage
1105 * const applyPromoCodeMutation = useApplyPromoCode();
1106 *
1107 * // Usage in component
1108 * function PromoCodeForm() {
1109 * const [code, setCode] = useState('');
1110 * const applyPromoCodeMutation = useApplyPromoCode();
1111 *
1112 * const handleApplyCode = (e: FormEvent) => {
1113 * e.preventDefault();
1114 *
1115 * applyPromoCodeMutation.mutate(
1116 * { code },
1117 * {
1118 * onSuccess: (cart) => {
1119 * console.log('Promo code applied:', cart);
1120 * setCode('');
1121 * // Show success message
1122 * },
1123 * onError: (error) => {
1124 * console.error('Failed to apply promo code:', error);
1125 * // Show error message
1126 * }
1127 * }
1128 * );
1129 * };
1130 *
1131 * return (
1132 * <form onSubmit={handleApplyCode}>
1133 * <input
1134 * type="text"
1135 * value={code}
1136 * onChange={(e) => setCode(e.target.value)}
1137 * placeholder="Enter promo code"
1138 * disabled={applyPromoCodeMutation.isPending}
1139 * />
1140 * <button type="submit" disabled={applyPromoCodeMutation.isPending}>
1141 * {applyPromoCodeMutation.isPending ? 'Applying...' : 'Apply'}
1142 * </button>
1143 * </form>
1144 * );
1145 * }
1146 * ```
1147 */
1148 export const useApplyPromoCode = () => {
1149 const queryClient = useQueryClient()
1150
1151 return useMutation({
1152 mutationFn: applyPromoCode,
1153 onSuccess: () => {
1154 // Update the cache with the fresh data from the server
1155 queryClient.invalidateQueries({ predicate: queryKeys.cart.predicate })
1156 },
1157 })
1158 }
1159
1160 /**
1161 * React hook to remove promotion codes from the cart.
1162 * Automatically invalidates cart cache on success.
1163 *
1164 * @returns Tanstack Query mutation object with mutate function and state
1165 *
1166 * @example
1167 * ```typescript
1168 * // Basic usage
1169 * const removePromoCodeMutation = useRemovePromoCode();
1170 *
1171 * // Usage in component
1172 * function AppliedPromoCode({ promoCode }) {
1173 * const removePromoCodeMutation = useRemovePromoCode();
1174 *
1175 * const handleRemoveCode = () => {
1176 * removePromoCodeMutation.mutate(
1177 * { code: promoCode.code },
1178 * {
1179 * onSuccess: (cart) => {
1180 * console.log('Promo code removed:', cart);
1181 * // Show success message
1182 * },
1183 * onError: (error) => {
1184 * console.error('Failed to remove promo code:', error);
1185 * // Show error message
1186 * }
1187 * }
1188 * );
1189 * };
1190 *
1191 * return (
1192 * <div>
1193 * <span>{promoCode.code} - {promoCode.amount} off</span>
1194 * <button
1195 * onClick={handleRemoveCode}
1196 * disabled={removePromoCodeMutation.isPending}
1197 * >
1198 * {removePromoCodeMutation.isPending ? 'Removing...' : 'Remove'}
1199 * </button>
1200 * </div>
1201 * );
1202 * }
1203 * ```
1204 */
1205 export const useRemovePromoCode = () => {
1206 const queryClient = useQueryClient()
1207
1208 return useMutation({
1209 mutationFn: removePromoCode,
1210 onSuccess: () => {
1211 // Update the cache with the fresh data from the server
1212 queryClient.invalidateQueries({ predicate: queryKeys.cart.predicate })
1213 },
1214 })
1215 }
1216 ```
1217
1218 </CodeTab>
1219 </CodeTabs>
1220
1221 With this setup, your cart mutations will provide immediate UI feedback with optimistic updates, while ensuring that the cart data is always fresh and consistent with the backend.