Skip to content

04: Implement cart

Cart is the first truly interactive part of the shop we'll implement.

Client-side state management

Imagine a user puts a product in a cart. This changes several parts of the app, like the cart icon in the top right corner or the stock amount still available for purchase.

As the components rendering those piece of UI can be in different parts of the application, a state management library is commonly used: something like Redux or MobX. We find MobX to be the simplest option and will use it in this tutorial.

Cart MobX store

Create stores/CartStore.ts:

// TODO

Make it available to the app via a React hook:

// TODO _app.js etc.

Update the UI with the "Add to Cart" button:

// TODO

Add an item to cart:

// TODO

React to changes in the cart icon:

// TODO

Also update the items in stock available:

// TODO

Congratulations, at this point, the e-shop behaves like a fully client-side application: user actions are reflected immediately in various places.

Next, you'll update the cart server-side and implement checkout.