1+ import React , { useState , useContext , useReducer , useEffect } from 'react'
2+ import cartItems from './data'
3+ import reducer from './reducer'
4+
5+
6+ const url = 'https://course-api.com/react-useReducer-cart-project'
7+
8+ const AppContext = React . createContext ( )
9+
10+ const AppProvider = ( { children } ) => {
11+ const [ cart , setCart ] = useState ( cartItems )
12+ const [ totalItems , setTotalItems ] = useState ( cart . length )
13+ const [ totalPrice , setTotalPrice ] = useState ( 0 )
14+
15+ // Function that clear all the items of the cart
16+ const clearCart = ( ) => {
17+ setCart ( [ ] )
18+ }
19+
20+ // Function that update the amount of items in the cart
21+ const updateAmount = ( id , amount ) => {
22+
23+ const cartItem = cart . find ( item => item . id === id ) //Get the item with the given id
24+ const newAmount = cartItem . amount + amount // calculate the new amount
25+
26+ // If the number of items is 0 remove the item from the cart
27+ if ( newAmount === 0 ) {
28+ setCart ( cart . filter ( item => item . id !== id ) )
29+ } else {
30+ setCart ( cart . map ( item => ( item . id === id ? { ...item , amount : newAmount } : item ) ) )
31+ }
32+ // update the total amount of items
33+ setTotalItems ( prevTotalItems => prevTotalItems + amount )
34+ }
35+
36+ // Function that calculate the totlal price of the items in the cart
37+ const calculateTotalPrice = ( ) => {
38+ let total = 0
39+ cart . forEach ( item => total += item . price * item . amount )
40+ setTotalPrice ( total . toFixed ( 2 ) )
41+ }
42+
43+ // Function that remove an item from the cart
44+ const removeItem = ( id ) => {
45+ const item = cart . find ( item => item . id === id )
46+ setTotalItems ( prevTotalItems => prevTotalItems - item . amount )
47+ setCart ( cart . filter ( item => item . id !== id ) )
48+ }
49+
50+ // Use Effect to update the total price everytime the cart, total items is updated
51+ useEffect ( ( ) => {
52+ calculateTotalPrice ( )
53+ } , [ cart , totalItems ] )
54+
55+ return (
56+ < AppContext . Provider
57+ value = { {
58+ cart,
59+ clearCart,
60+ totalItems,
61+ updateAmount,
62+ totalPrice,
63+ removeItem
64+ } }
65+ >
66+ { children }
67+ </ AppContext . Provider >
68+ )
69+ }
70+ // make sure use
71+ export const useGlobalContext = ( ) => {
72+ return useContext ( AppContext )
73+ }
74+
75+ export { AppProvider }
0 commit comments