7. Cart context
Create, retrieve, and share the cart across screens.
On this page
In this step, you'll create a cart context to manage the customer's cart state throughout the app. The cart context will allow you to create, manage, and complete the cart.
Create Cart Context
Create the file context/cart-context.tsx with the following content:
tsx
You define the CartContext with the following properties that child components can use:
cart: The current cart object.addToCart: A function to add an item to the cart.updateItemQuantity: A function to update the quantity of an item in the cart.removeItem: A function to remove an item from the cart.refreshCart: A function to refresh the cart data from the backend.clearCart: A function to clear the cart, which is useful after checkout.loading: A boolean indicating whether a cart operation is in progress.error: An error message if a cart operation fails.
You also define the CartProvider component that will wrap the app and provide the cart context to its children.
Next, you'll implement the logic to load the cart from the Aiminaabee backend. Replace the // TODO load cart comment with the following:
tsx
The loadCart function creates or retrieves the saved cart from the Aiminaabee backend using the JS SDK. This function runs when the component mounts using the useEffect hook.
Next, you'll implement the logic to handle region updates, as the cart's region must match the selected region.
Replace the // TODO handle region update comment with the following:
tsx
You add an effect that runs whenever the selected region changes. If the cart's region doesn't match the selected region, it updates the cart's region using the JS SDK.
Next, you'll implement the cart operations that you defined in the context type. Replace the // TODO implement cart operations comment with the following:
tsx
You define the following cart operation functions:
addToCart: Adds an item to the cart by creating a line item.updateItemQuantity: Updates the quantity of an item in the cart.removeItem: Removes an item from the cart.refreshCart: Refreshes the cart data from the backend.clearCart: Clears the cart and creates a new one.
You also add a return statement providing the context values to child components using the CartContext.Provider.
Finally, you'll create a custom hook in the same file to access the cart context easily. Replace the // TODO add useCart hook comment with the following:
tsx
The useCart hook retrieves the context value using useContext. It throws an error if used outside of a CartProvider.
Wrap App in Cart Provider
Next, you'll wrap the app in the CartProvider to provide the cart context to all components.
In app/_layout.tsx, add the following import at the top of the file:
tsx
Then, in the RootLayout's return statement, add the CartProvider as a child of the RegionProvider and a parent of the Stack component:
tsx
Child components can now access the cart context using the useCart hook.
Next: 8. Home screen