0

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))
}
Andrey Popov
  • 7,362
  • 4
  • 38
  • 58
Yollo
  • 79
  • 2
  • 9

2 Answers2

0

You need to use useEffect in order to listen for updates on the property. From the docs:

import React, { useState, useEffect } from 'react';

function Example() {
  const [count, setCount] = useState(0);

  // Similar to componentDidMount and componentDidUpdate:
  useEffect(() => {
    // Update the document title using the browser API
    document.title = `You clicked ${count} times`;
  });

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

Basically you'd call your addToCard method from within the useEffect handler. Even more info here: How can React useEffect watch and update state?

Andrey Popov
  • 7,362
  • 4
  • 38
  • 58
  • this function `addToCart` is in another file, and I update it from `Products` page. I mean the function and the button that update the state are in different files – Yollo Jun 10 '21 at 16:28
0

In order to wait for the state to update and then execute then function, you need to use useEffect with the state as dependency

...
useEffect(()=>{
   addToCart(user, product)
},[chosenImage])
Toby
  • 119
  • 1
  • 8
  • okay but it seems I can't make the function with `addToCart(user, product)` , it don't accept the surrounding `{ }` . – Yollo Jun 10 '21 at 19:00
  • what do you mean? You simple create function `addToCart` outside of the useEffect, and inside the hook, you just have to call it and pass in the parameters – Toby Jun 11 '21 at 18:29