Skip to content

Commit 41dcdbf

Browse files
committed
feat: 12.CartUseReducer: context: Implement the function that fetch data
1 parent b4adfa1 commit 41dcdbf

File tree

2 files changed

+13
-30
lines changed

2 files changed

+13
-30
lines changed

src/projects/12.CartUseReducer/context.js

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
import React, { useState, useContext, useReducer, useEffect } from 'react'
2-
import cartItems from './data'
32
import reducer from './reducer'
43

54
const url = 'https://course-api.com/react-useReducer-cart-project'
@@ -8,7 +7,7 @@ const AppContext = React.createContext()
87
// Reducer initial state
98
const initialState = {
109
loading: false,
11-
cart: cartItems,
10+
cart: [],
1211
total: 0,
1312
amount: 0
1413
}
@@ -32,6 +31,18 @@ const AppProvider = ({ children }) => {
3231
dispatch ({ type: 'UPDATE_AMOUNT', payload: { id, type, amount }})
3332
}
3433

34+
// Function that fetch date and dispatch the action of displaying items of the cart
35+
const fetchData = async() => {
36+
dispatch({ type: 'LOADING' })
37+
const cart = await fetch(url).response.json()
38+
dispatch({ type: 'DISPLAY_ITEMS', payload: cart })
39+
}
40+
41+
// Add the useEffect that fetch data
42+
useEffect(() => {
43+
fetchData()
44+
}, [])
45+
3546
return (
3647
<AppContext.Provider
3748
value={{

src/projects/12.CartUseReducer/data.js

Lines changed: 0 additions & 28 deletions
This file was deleted.

0 commit comments

Comments
 (0)