i wrap all of my components and screen inside the CartProvide but its still show “useCart must be used within a CartProvider”
I wanna show the receipt of the total orders but it show the error
below is my code for CartContext
type CartItem = {
name: string;
price: number;
imageUrl: any;
type: "FOOD" | "DRINK";
};
interface CartContextType {
orders: CartItem[];
addToCart: (item: CartItem) => void;
clearCart: () => void;
}
const CartContext = createContext<CartContextType | undefined>(undefined);
export const CartProvider = ({ children }: { children: React.ReactNode }) => {
const [orders, setOrders] = useState<CartItem[]>([]);
const addToCart = (item: CartItem) => {
setOrders((prevOrders) => [...prevOrders, item]);
};
const clearCart = () => {
setOrders([]);
};
return (
<CartContext.Provider value={{ orders, addToCart, clearCart }}>
{children}
</CartContext.Provider>
);
};
export const useCart = () => {
const context = useContext(CartContext);
if (!context) {
throw new Error("useCart must be used within a CartProvider");
}
return context;
};
my index
const index = () => {
return (
<CartProvider>
<View style={{ flex: 1 }}>
<Greet />
<Menu />
</View>
</CartProvider>
);
};
and my Cart screen
const Cart = () => {
const { orders } = useCart(); // Fetch cart orders
const total = orders.reduce((sum, item) => sum + item.price, 0);
return (
<CartProvider>
<ScrollView>
<Header />
<CartComp
itemPrices={orders.map((item) => item.price)}
menus={orders.map((item) => item.name)}
total={total}
/>
</ScrollView>
</CartProvider>
);
};
i already wrap all of that inside of CartProvider but it still show the error, how this could happen?