Skip to content

Instantly share code, notes, and snippets.

@zc0rp10
Last active December 28, 2020 09:04
Show Gist options
  • Save zc0rp10/9bb609a19122a95c9d0bed64b7382b9c to your computer and use it in GitHub Desktop.
Save zc0rp10/9bb609a19122a95c9d0bed64b7382b9c to your computer and use it in GitHub Desktop.
Functions for manipulating a Shopping Cart made up of an array, held in State. #react

State

[ cartItems, setCartItems ] = useState([])

Add To Cart

function addToCart(newItem) {
        setCartItems(prevItems => [...prevItems, newItem])
}

Remove From Cart

function removeFromCart(itemId) {
        setCartItems(prevItems => prevItems.filter(item => item.id !== itemId))
}

Empty Cart

function emptyCart() {
        setCartItems([])
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment