When I use totalQuantity inside the useState() hook ,it returns undefined. But if I assign totalQuantity = 100, totalQuantity = 200 etc. inside the useState() hook, it displays the number. So why useState(totalQuantity) returns undefined whenever I assign totalQuantity the option chained value as the initial count? Here is the code:
const inventories = useInventory();
const { inventoryId } = useParams();
const selectedInventory = inventories.find(
(inventory) => inventory._id === inventoryId
);
const totalQuantity = selectedInventory?.quantity;
console.log(totalQuantity);
const [carQuantity, setCarQuantity] = useState(totalQuantity);
const quantityDecreaser = () => {
if (carQuantity > 0) {
setCarQuantity(carQuantity - 1);
const remainingQuantity = carQuantity - 1;
const data = { remainingQuantity };
fetch(`http://localhost:5000/inventories/${inventoryId}`, {
method: "PUT",
headers: {
"content-type": "application/json",
},
body: JSON.stringify(data),
})
.then((res) => res.json())
.then((result) => {
console.log(result);
});
}
};```
I fixed it using useEffect(). Maybe the setCarQuantity() was failed to set the value immediately and after using useEffect() it listens to the state change.