How can I make my function addToCart
wait till the chosenImage
state update ? In first console.log which is out of the function, I can see the updated state, but the console.log inside returns empty string.
Note: addToCart
function and the state are not in the same directory as the button that update the state.
const [chosenImage, setChosenImage] = useState('');
console.log(chosenImage)
useEffect(() => {
function addToCart(user, product) {
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))
}
}, [chosenImage])