Last active
October 8, 2024 05:58
-
-
Save jimode/c1d2d4c1ab33ba1b7be8be8c50d64555 to your computer and use it in GitHub Desktop.
Providing Context and Local Storage Using Hooks
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Providing Context | |
// ================== | |
import React, {useState, useEffect} from "react" | |
const Context = React.createContext() | |
function ContextProvider({children}) { | |
const [allPhotos, setAllPhotos] = useState([]) | |
const [cartItems, setCartItems] = useState([]) | |
// Local Storage: setting & getting data | |
useEffect(() => { | |
const cartItemsData = JSON.parse(localStorage.getItem('cartItems')) | |
if (cartItemsData) { | |
setCartItems(cartItemsData) | |
} | |
}, []) | |
useEffect(() => { | |
localStorage.setItem('cartItems', JSON.stringify(cartItems)) | |
}, [cartItems]) | |
const url = "https://raw.githubusercontent.com/bobziroll/scrimba-react-bootcamp-images/master/images.json" | |
useEffect(() => { | |
fetch(url) | |
.then(res => res.json()) | |
.then(data => setAllPhotos(data)) | |
}, []) | |
function toggleFavorite(id) { | |
const updatedArr = allPhotos.map(photo => { | |
if(photo.id === id) { | |
return {...photo, isFavorite: !photo.isFavorite} | |
} | |
return photo | |
}) | |
setAllPhotos(updatedArr) | |
} | |
function addToCart(newItem) { | |
setCartItems(prevItems => [...prevItems, newItem]) | |
} | |
function removeFromCart(id) { | |
setCartItems(prevItems => prevItems.filter(item => item.id !== id)) | |
} | |
return ( | |
<Context.Provider value={{allPhotos, toggleFavorite, cartItems, addToCart, removeFromCart}}> | |
{children} | |
</Context.Provider> | |
) | |
} | |
export {ContextProvider, Context} | |
// Retrieving state using useContext | |
// ================================= | |
import React, {useState, useContext} from "react" | |
import PropTypes from "prop-types" | |
import {Context} from "../Context" | |
function Image({className, img}) { | |
const [hovered, setHovered] = useState(false) | |
const {toggleFavorite, addToCart, cartItems, removeFromCart} = useContext(Context) | |
function heartIcon() { | |
if(img.isFavorite) { | |
return <i className="ri-heart-fill favorite" onClick={() => toggleFavorite(img.id)}></i> | |
} else if(hovered) { | |
return <i className="ri-heart-line favorite" onClick={() => toggleFavorite(img.id)}></i> | |
} | |
} | |
function cartIcon() { | |
const alreadyInCart = cartItems.some(item => item.id === img.id) | |
if(alreadyInCart) { | |
return <i className="ri-shopping-cart-fill cart" onClick={() => removeFromCart(img.id)}></i> | |
} else if(hovered) { | |
return <i className="ri-add-circle-line cart" onClick={() => addToCart(img)}></i> | |
} | |
} | |
return ( | |
<div | |
className={`${className} image-container`} | |
onMouseEnter={() => setHovered(true)} | |
onMouseLeave={() => setHovered(false)} | |
> | |
<img src={img.url} className="image-grid"/> | |
{heartIcon()} | |
{cartIcon()} | |
</div> | |
) | |
} | |
Image.propTypes = { | |
className: PropTypes.string, | |
img: PropTypes.shape({ | |
id: PropTypes.string.isRequired, | |
url: PropTypes.string.isRequired, | |
isFavorite: PropTypes.bool | |
}) | |
} | |
export default Image |
Thanks a lot, was battling for a solution for days now
How do i use this, but without passing a fixed value to my key
I need to access the storage inside the useEffect, but my getItem doesn't receive a fixed string key
Nice one!, Thanks a lot
This doesn't seem to work for me. When the page reloads, it calls the use effect hook which pulls the data from local storage and after it calls the use effect hook with cartItems=[] from the initialisation of useState([]) which then wipes local storage and sets cartItems to []
Thank man
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you!