Skip to content

Commit

Permalink
Allow calling the cart .get() method right after cart mutation meth…
Browse files Browse the repository at this point in the history
…ods (#1865)
  • Loading branch information
blittle committed Mar 18, 2024
1 parent 3766b26 commit 3c8a731
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 3 deletions.
27 changes: 27 additions & 0 deletions .changeset/itchy-weeks-search.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
---
'@shopify/hydrogen': patch
---

Allow calling the cart `.get()` method right after creating a new cart with
one of the mutation methods: `create()`, `addLines()`, `updateDiscountCodes()`, `updateBuyerIdentity()`, `updateNote()`, `updateAttributes()`, `setMetafields()`.

```ts
import {
createCartHandler,
cartGetIdDefault,
cartSetIdDefault,
} from '@shopify/hydrogen';

const cartHandler = createCartHandler({
storefront,
getCartId: cartGetIdDefault(request.headers),
setCartId: cartSetIdDefault(),
cartQueryFragment: CART_QUERY_FRAGMENT,
cartMutateFragment: CART_MUTATE_FRAGMENT,
});

await cartHandler.addLines([{merchandiseId: '...'}]);
// This change fixes a bug where `cart` would be null, even though a
// new cart was created when adding a line item
const cart = await cartHandler.get();
```
13 changes: 13 additions & 0 deletions packages/hydrogen/src/cart/createCartHandler.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -399,4 +399,17 @@ describe('createCartHandler', () => {

expect(result.cart).toHaveProperty('id', 'gid://shopify/Cart/c1-456');
});

it('stores the cartId in memory when a new cart is created and returns that result if available', async () => {
const cart = getCartHandler();

await cart.addLines([
{
merchandiseId: '1',
quantity: 1,
},
]);

expect(await cart.get()).toHaveProperty('id', 'c1-new-cart-id');
});
});
15 changes: 12 additions & 3 deletions packages/hydrogen/src/cart/createCartHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,22 +96,31 @@ export function createCartHandler<TCustomMethods extends CustomMethodsBase>(
options: CartHandlerOptions | CartHandlerOptionsWithCustom<TCustomMethods>,
): CartHandlerReturn<TCustomMethods> {
const {
getCartId,
getCartId: _getCartId,
setCartId,
storefront,
customerAccount,
cartQueryFragment,
cartMutateFragment,
} = options;

let cartId = _getCartId();

const getCartId = () => cartId || _getCartId();

const mutateOptions = {
storefront,
getCartId,
cartFragment: cartMutateFragment,
};

const cartId = getCartId();
const cartCreate = cartCreateDefault(mutateOptions);
const _cartCreate = cartCreateDefault(mutateOptions);

const cartCreate: CartCreateFunction = async function (...args) {
const result = await _cartCreate(...args);
cartId = result?.cart?.id;
return result;
};

const methods: HydrogenCart = {
get: cartGetDefault({
Expand Down

0 comments on commit 3c8a731

Please sign in to comment.