React Native
Putting it together
Combine all parts into a working e-commerce app.
Putting it together
In the final step we wire all the pieces together. We add a useCart hook: () => useContext(CartContext). This hook gives a single point of access to the cart; every screen gets cart and addToCart without prop drilling.
We put a Cart: {cart.length} counter in the header and an Add to cart button on the detail. The button calls addToCart(selected); the product is added and the counter updates at once. The app now has a single flow.
Exercise Add useCart and the add-to-cart button
Add a useCart hook (return useContext(CartContext)). In App reach the cart with const { cart, addToCart } = useCart(); show Cart: {cart.length} in the header; add a <Text onPress={() => addToCart(selected)}>Add to cart</Text> button on the detail.
Show example solution
import React, { createContext, useContext, useState } from 'react';
import { FlatList, Text, View } from 'react-native';
const products = [
{ id: '1', name: 'Pen', price: 20 },
{ id: '2', name: 'Notebook', price: 35 },
]
const CartContext = createContext();
function CartProvider({ children }) {
const [cart, setCart] = useState([]);
const addToCart = (item) => setCart([...cart, item]);
return (
<CartContext.Provider value={{ cart, addToCart }}>
{children}
</CartContext.Provider>
);
}
function useCart() {
return useContext(CartContext);
}
export default function App() {
const [selectedId, setSelectedId] = useState(null);
const selected = products.find((p) => p.id === selectedId);
const { cart, addToCart } = useCart();
if (selected) {
return (
<View>
<Text>{selected.name}</Text>
<Text onPress={() => setSelectedId(null)}>Back</Text>
<Text onPress={() => addToCart(selected)}>Add to cart</Text>
</View>
);
}
return (
<View>
<Text>Cart: {cart.length}</Text>
<FlatList
data={products}
keyExtractor={(item) => item.id}
renderItem={({ item }) => (
<Text onPress={() => setSelectedId(item.id)}>{item.name}</Text>
)}
/>
</View>
);
}
The app is complete
Now all the pieces are together: product data, a FlatList, a state-driven detail switch and a Context cart. useCart gives a single point of access to the cart; the counter and the button make it visible.
This structure is the same in a real app: data, list, detail and a shared cart. If you want to add a navigation library, you can swap selectedId for React Navigation; the Context stays the same.
Test yourself
-
What does the useCart hook return?
- The result of useContext(CartContext)
- A new Context
- The products array
- The selected product
Show answer
The result of useContext(CartContext) — useCart returns useContext(CartContext).
-
Write the cart counter
<Text>Sepet: {____}</Text>
Show answer
<Text>Sepet: {cart.length}</Text>
-
Match the integration concepts
- useCart
- Reaches the cart
- cart.length
- Cart count
- addToCart(selected)
- Adds product
- CartProvider
- Wraps the app
Next lesson: Animated.Value