-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAppContext.js
48 lines (39 loc) · 1.38 KB
/
AppContext.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import React from "react"
import {useState, useEffect} from "react"
import "./styles.css"
const Context = React.createContext()
function ContextProvider({children}){
const url = "https://raw.githubusercontent.com/sergiuSsg/Picosa-React/main/images.json"
const [allPhotos, setAllPhotos] = useState([])
const [cartItems, setCartItems] = useState([])
function toggleFavorite(id){
const tempArray = allPhotos.map(photo => {
if(photo.id === id) {
return {...photo, isFavorite: !photo.isFavorite}
}
return photo
})
setAllPhotos(tempArray)
}
function addToCart(image){
setCartItems(prevCart => [...prevCart, image])
}
function removeFromCart(id){
setCartItems(prevCartItems => prevCartItems.filter(item => item.id !== id))
}
function emptyCart(){
setCartItems([])
}
useEffect(() => {
fetch(url)
.then(response => response.json())
.then(data => setAllPhotos(data))
}, [])
const providerValue = {allPhotos, setAllPhotos, toggleFavorite, cartItems, setCartItems, addToCart, removeFromCart, emptyCart}
return(
<Context.Provider value={providerValue}>
{children}
</Context.Provider>
)
}
export {ContextProvider, Context}