React useState() hook returns undefined when using option chained value as initial count

871 views Asked by At

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);
        });
    }
  };```
4

There are 4 answers

0
FID On BEST ANSWER

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]); 
1
Ayoub On

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

1
arthurg On

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);
1
Hakob Sargsyan On

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);