Skip to content

Instantly share code, notes, and snippets.

@PrimeTimeTran
Created July 21, 2019 07:40
Show Gist options
  • Save PrimeTimeTran/ee9fdf37293b439aa6c785e4395a288d to your computer and use it in GitHub Desktop.
Save PrimeTimeTran/ee9fdf37293b439aa6c785e4395a288d to your computer and use it in GitHub Desktop.
import React, { useState, useEffect } from 'react';
import './App.css';
function App() {
const [cart, setCartItem] = useState({ items: [] })
const getCart = async() => {
const cart = await localStorage.getItem('cart')
if (cart) {
const cartObject = {
id: 1,
items: [
{ name: 'Football', price: 29.99 },
{ name: 'Flags', price: 19.99 }
]
}
const cart = localStorage.getItem('cart')
setCartItem(JSON.parse(cart))
} else {
console.log('Dont have a cart id')
}
}
const addItem = async () => {
let localCart = await localStorage.getItem('cart')
localCart = await JSON.parse(localCart)
const item = { name: 'Flags', price: 19.99 }
localCart.items.push(item)
localStorage.setItem('cart', JSON.stringify(localCart))
setCartItem(localCart)
}
useEffect(() => {
getCart()
}, [])
return (
<div className="App">
{cart.items.map(item => {
return (
<div>
<h1>{item.name}</h1>
<h1>{item.price}</h1>
</div>
)
})}
<button onClick={addItem}>Add item</button>
</div>
);
}
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment