You need to store things in localStorage as a string. You also need to wait for the API response, axios.get
returns a Promise.
async function handleClick(id) {
try {
const chosen_product = await axios.get(`http://localhost:8000/api/products/${id}`)
setCart(cart + {chosen_product}) // This is wrong, can't add array to object
localStorage.setItem("cartItems", JSON.stringify(cart)) // This is wrong, cart will still be the previous value
} catch (err) {
console.error(err)
}
}
In fact you already have this code structure in getProducts...
Also this code makes no sense:
setCart(cart + {chosen_product})
You can't add an object to an array.
Also setting cart
straight after setCart
won't work and cart
will still be your previous value at that point, simplest solution is to create a variable for your new state.
const newCart = cart.concat(chosen_product);
setCart(newCart);
localStorage.setItem("cartItems", JSON.stringify(newCart));
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…