0

I'm trying to update the cars array whenever the Add button is clicked. I see that new object is added to updatedCars array but when I try to set the state with it, the cars state won't get updated.

I still see the initial state even after adding a new object in the array.

export default function App() {
  const [cars, setCars] = useState([{ name: "Audi", type: "sedan" }]);
  
  const handleAdd = () => {
    const newCar = { name: "Benz", type: "sedan" };
    const updatedCars = [...cars, newCar];
    console.log("updatedCars", updatedCars);
    setCars(updatedCars);
    console.log("result", cars);
  };
  
  return (
    <div className="App">
      <button onClick={handleAdd}>Add</button>
    </div>
  );
}

I created a working example using CodeSandbox. Could anyone please help?

coderpc
  • 4,119
  • 6
  • 51
  • 93

1 Answers1

1

setCars is the asynchronous method, and you can't get the updated value of cars immediately after setCars()

setCars(updatedCars);
console.log(cars); //This will console old value of `cars`

You should use useEffect with adding a cars dependency to check updated value.

useEffect(() => {
  console.log(cars);
}, [cars]);
wangdev87
  • 8,611
  • 3
  • 8
  • 31