I want to make my function await till chosenImage
state update. I can see the updated state in the console.log out of the addToCart
function, but the console.log inside returns empty string. How can I make it await till state update?
Here is what I mean:
const [chosenImage, setChosenImage] = useState('');
console.log(chosenImage)
const addToCart = (user, product) => {
console.log(chosenImage)
const cartProduct = {
_id: product._id,
name: product.name,
description: product.description,
processor: product.processor,
ram: product.ram,
storage: product.storage,
price: product.price,
type: product.type,
likes: product.likes,
colors: product.colors,
images: chosenImage
}
fetch(`${API}/cart/usercart`, {
method:"POST",
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify([user._id, cartProduct])
})
.then(response => response.json())
.then(response => {
const updatedCart = response.cart;
setUser(oldState => ({...oldState, cart: [updatedCart]}))
localStorage.setItem("cart", JSON.stringify(updatedCart))
})
.catch(error => console.log(error))
}