0

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])
Yollo
  • 79
  • 2
  • 9
  • React state updates are asynchronous, but the state updater function is completely synchronous, it can't be awaited. Typically you use an `useEffect` to issue a side-effect with the updated state on the next render cycle. – Drew Reese Jun 10 '21 at 19:40
  • So how can I make it work ? – Yollo Jun 10 '21 at 19:44
  • Where is the chosen image being updated in the action? If the add to cart action is dependent on the chosen image being updated, use an `useEffect` hook with appropriate dependency. – Drew Reese Jun 10 '21 at 19:47
  • I get it. But in useEffect I can't make a function. I try it but it doesn't accept the `(user, product)`, also doesn't accept the `{}` – Yollo Jun 10 '21 at 19:51
  • Of course you can make a function. What is `{}` and what doesn't accept it? – Drew Reese Jun 10 '21 at 19:57
  • I can't provide the function in provider `value={[user, setUser, addToCart, ...`. Check my updated question. If I'm wrong somewhere – Yollo Jun 10 '21 at 20:01

1 Answers1

1

Use the useEffect hook.

useEffect (()=> addToCart(user, product); ,[chosenImage]);

Gaurav
  • 61
  • 1
  • 2
  • I try it but in useEffect I can't pass (user, product). Also I can't make a function inside like `addToCart(user, product) {}` it doesn't accept the `{}` – Yollo Jun 10 '21 at 19:33