Skip to content

Commit

Permalink
Expose cartReady (#1885)
Browse files Browse the repository at this point in the history
* Convert cartReady to a state variable so it can be exposed and reacted to in components that use rely on it.
  • Loading branch information
celsowhite committed Mar 26, 2024
1 parent 062d6be commit e50f434
Show file tree
Hide file tree
Showing 4 changed files with 15 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .changeset/tame-cobras-sort.md
@@ -0,0 +1,5 @@
---
'@shopify/hydrogen-react': patch
---

Expose `cartReady` state from the cart context.
3 changes: 3 additions & 0 deletions packages/hydrogen-react/src/CartProvider.stories.tsx
Expand Up @@ -20,6 +20,7 @@ function CartComponent() {
discountCodes,
linesAdd,
cartCreate,
cartReady,
linesUpdate,
linesRemove,
noteUpdate,
Expand Down Expand Up @@ -51,6 +52,8 @@ function CartComponent() {
<h1>This is your current cart</h1>
<h3>Cart status</h3>
<p>{status}</p>
<h3>Cart ready</h3>
<p>{cartReady ? 'true' : 'false'}</p>
<h3>Fetched from local storage with this cart id</h3>
<p>{localStorageId}</p>
<h3>Cart lines</h3>
Expand Down
5 changes: 5 additions & 0 deletions packages/hydrogen-react/src/CartProvider.tsx
Expand Up @@ -271,6 +271,7 @@ export function CartProvider({
});

const cartReady = useRef(false);
const [isCartReady, setIsCartReady] = useState(false);
const cartCompleted = cartState.matches('cartCompleted');

const countryChanged =
Expand Down Expand Up @@ -302,6 +303,8 @@ export function CartProvider({
}
}
cartReady.current = true;
// Providing a separate cart ready state variable to avoid re-renders in this logic while still being able to pass the reactive status through context.
setIsCartReady(true);
}
}, [cart, cartReady, cartSend]);

Expand Down Expand Up @@ -393,6 +396,7 @@ export function CartProvider({
error: cartDisplayState?.context?.errors,
totalQuantity: cartDisplayState?.context?.cart?.totalQuantity ?? 0,
cartCreate,
cartReady: isCartReady,
linesAdd(lines: CartLineInput[]): void {
if (cartDisplayState?.context?.cart?.id) {
onCartReadySend({
Expand Down Expand Up @@ -455,6 +459,7 @@ export function CartProvider({
};
}, [
cartCreate,
isCartReady,
cartDisplayState?.context?.cart,
cartDisplayState?.context?.errors,
cartDisplayState.value,
Expand Down
2 changes: 2 additions & 0 deletions packages/hydrogen-react/src/cart-types.ts
Expand Up @@ -62,6 +62,8 @@ interface CartActions {
totalQuantity?: number;
/** The fragment used to query the cart object for all queries and mutations. */
cartFragment: string;
/** A boolean indicating if the cart is ready to be interacted with. */
cartReady?: boolean;
}

export type Cart = PartialDeep<CartBase, {recurseIntoArrays: true}>;
Expand Down

0 comments on commit e50f434

Please sign in to comment.