Part 3 - Add Product Details, Favorites, and a Cart to React Native
Add variants, favorites, quantity controls, and a shopping cart to the MugMori React Native app with Context and useReducer.
Add Product Details, Favorites, and a Cart to React Native
A catalog can show products, but customers need a place to make choices. This article adds product details, favorites, and a cart using React Context and useReducer.
Model cart items
export type CartItem = {
cupId: string;
quantity: number;
size: string;
color: string;
};
export type CartState = {
items: CartItem[];
};
A cart item is a cup plus a quantity and variant. It does not need to copy the whole product object.
Use a reducer
type CartAction =
| { type: 'add'; item: CartItem }
| { type: 'remove'; cupId: string };
function cartReducer(state: CartState, action: CartAction): CartState {
switch (action.type) {
case 'add':
return { ...state, items: [...state.items, action.item] };
case 'remove':
return {
...state,
items: state.items.filter((item) => item.cupId !== action.cupId),
};
default:
return state;
}
}
A reducer makes allowed transitions visible and gives tests a small pure function to exercise.
Share cart state
Wrap the navigation tree with CartProvider so the detail and cart screens use the same state. Favorites can use local state until persistence becomes a real requirement.
The detail screen should show a larger image, print design, size and color variants, price, stock state, quantity controls, and favorite/add-to-cart actions.
Keep quantities safe
The quantity control should never allow zero to become a hidden cart item. If the customer wants zero, provide a visible remove action. If a product is out of stock, disable the add button and explain why.
Paper's IconButton, Button, Snackbar, and Badge components can communicate these states.
Calculate totals carefully
const subtotal = items.reduce((total, item) => {
const cup = cupsById.get(item.cupId);
return total + (cup?.salePrice ?? cup?.price ?? 0) * item.quantity;
}, 0);
The mobile client can display a subtotal, but a real checkout must validate prices on the server.