diff --git a/.changeset/cart-get-respects-cartid.md b/.changeset/cart-get-respects-cartid.md new file mode 100644 index 0000000000..7e425ac2eb --- /dev/null +++ b/.changeset/cart-get-respects-cartid.md @@ -0,0 +1,5 @@ +--- +"@shopify/hydrogen": patch +--- + +Fix `cartGetDefault` not respecting the `cartId` argument. The returned function accepts an optional `cartInput.cartId`, but the implementation called `getCartId()` unconditionally and then early-returned `null` when that was falsy — so a caller passing `{cartId: '…'}` with no cart cookie got `null` back. The resolved cart id now prefers `cartInput.cartId` before falling back to `getCartId()`, and the GraphQL `variables` spread order was swapped so the resolved cart id always wins over an explicit `{cartId: undefined}` in the input. diff --git a/packages/hydrogen/src/cart/queries/cartGetDefault.test.ts b/packages/hydrogen/src/cart/queries/cartGetDefault.test.ts index 1f2f2b4b98..4d9795cea5 100644 --- a/packages/hydrogen/src/cart/queries/cartGetDefault.test.ts +++ b/packages/hydrogen/src/cart/queries/cartGetDefault.test.ts @@ -53,6 +53,28 @@ describe('cartGetDefault', () => { expect(result).toHaveProperty('id', 'gid://shopify/Cart/c1-456'); }); + it('should use the cartId passed in when getCartId returns undefined', async () => { + const cartGet = cartGetDefault({ + storefront: mockCreateStorefrontClient(), + getCartId: () => undefined, + }); + + const result = await cartGet({cartId: 'gid://shopify/Cart/c1-456'}); + + expect(result).toHaveProperty('id', 'gid://shopify/Cart/c1-456'); + }); + + it('should fall back to getCartId when cartInput.cartId is explicitly undefined', async () => { + const cartGet = cartGetDefault({ + storefront: mockCreateStorefrontClient(), + getCartId: () => CART_ID, + }); + + const result = await cartGet({cartId: undefined}); + + expect(result).toHaveProperty('id', CART_ID); + }); + describe('run with customerAccount option', () => { it('should add logged_in search param to checkout link if customer is logged in', async () => { const cartGet = cartGetDefault({ diff --git a/packages/hydrogen/src/cart/queries/cartGetDefault.ts b/packages/hydrogen/src/cart/queries/cartGetDefault.ts index 71ddee722b..12ca9f15c4 100644 --- a/packages/hydrogen/src/cart/queries/cartGetDefault.ts +++ b/packages/hydrogen/src/cart/queries/cartGetDefault.ts @@ -63,14 +63,14 @@ export function cartGetDefault({ cartFragment, }: CartGetOptions): CartGetFunction { return async (cartInput?: CartGetProps) => { - const cartId = getCartId(); + const cartId = cartInput?.cartId ?? getCartId(); if (!cartId) return null; const [isCustomerLoggedIn, {cart, errors}] = await Promise.all([ customerAccount ? customerAccount.isLoggedIn() : false, storefront.query<{cart: Cart | null}>(CART_QUERY(cartFragment), { - variables: {cartId, ...cartInput}, + variables: {...cartInput, cartId}, cache: storefront.CacheNone(), }), ]);