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?