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);
});
}
};```
CodePudding user response:
It seems like your selectedInventory is returning undefined and so is
const totalQuantity = selectedInventory?.quantity;
This might me caused by a wrong or unexisting inventoryId.
Check if selectedInventory has correct data and you can also use a default value here:
const [carQuantity, setCarQuantity] = useState(totalQuantity || defaultValue);
CodePudding user response:
maybe your find method return undefined therefore state is undefined
const get = (data) => {
const inventoryId = 8;
const selectedInventory = data.find(
inventory => inventory.id === inventoryId
);
return selectedInventory;
}
const totalQuantity = get([{id: 4,quantity:888 }, {id: 8, quantity:88 }, {id: 9, quantity:787}]);
const [carQuantity, setCarQuantity] = React.useState(totalQuantity);
console.log(carQuantity);
CodePudding user response:
it might a be type problem since you're using === to check for equality, if your inventory._id is a number, since useParams hook will return a string.
use the double equal sign to check for value only inventory._id == inventoryId
OR
parse the inventoryId to a number with the plus like so inventory._id === inventoryId
CodePudding user response:
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.
const [carQuantity, setCarQuantity] = useState(totalQuantity);
useEffect(() => {
setCarQuantity(totalQuantity);
}, [totalQuantity]);