States Not being updated as aspected

So basically I am creating a invoicing application where user can create bills ( add items to bills by scanning bar code ) user can also add item by specifically typing the itemid ( which exists in their inventory )

• First Function

const handleAddItemById = async (provideditemid) => {
    const AuthToken = localStorage.getItem("AuthToken");
    const itemId = provideditemid ? provideditemid : billDetails.itemId;
    console.log(itemId)
    const response = await fetch(
      `${Base_Url}/inventory/getone?itemId=${itemId}`,
      {
        method: "GET",
        headers: {
          "content-type": "application/json",
          authorization: AuthToken,
        },
      }
    );
    const json = await response.json();
    if (response.ok){
      addItem(json.item);
    } else {
      toast.error(json.msg);
    }
    cleanInputid();
  };

( This function can be called without an argument or with an argument, it gets called without argument when i add item by input method ( that is by manually typing input id ) and it gets called with a argument ( argument is a itemid ) when i scan barcode )
if the response if okay this function calls the “addItem” function with the whole item object as argument.
The json.item looks something like this —
{user : “[email protected]”
Itemname :”donut”
price :30
Quantity :4
ItemsOnDiscount :2
DiscountP :10
DiscountV :3
ItemId :21}

First Function Now calls Second Function —

• Second function

  const addItem = async (newItem) => {
    const ItemExistsInPrevAdded = alreadyAddedbillItems.some(
      (existingItem) => existingItem.ItemId === newItem.ItemId
  );
  console.log("alreadyAddedbillItems : ", alreadyAddedbillItems)
  console.log("PrevaddeditemsExists :" ,ItemExistsInPrevAdded)
    if (ItemExistsInPrevAdded){
        addItemsFromAlreadyAddedItems(newItem,true)
    } else {
        console.log(newItem)
        setalreadyAddedbillItems(previtems => [...previtems,newItem])
        addItemsFromAlreadyAddedItems(newItem,false)
    }
  };

I have a state “alreadyAddedbillItems” which is a array of objects ( item objects )
When a new item is added i check in this array first if the item (same id) already exists in this state variable or not
(if it is not then it means the item of this specific id is being added to bill for first time)
so the “else” block of the code gets executed ( which now actually adds this item to “alreadyAddedbillItems” so next time the “if” block is executed
All till now is working fine with if i try to add a item using input method (manually typing id )
But When i try to add a item by scanning the qr code it works fine for first time (means the else block does gets executed ) but the time i add item using the qr code again idk why it again goes to else block so i tried logging “alreadyAddedbillItems” but guess what it was empty idk why…

• Third Function (Last function)

const addItemsFromAlreadyAddedItems = async (Existingitem,bool) => {
        if(bool){
          const ExistingBillItem = billItems.find((item) => item.ItemId === Existingitem.ItemId)
          let ExistingBillItemNoDiscount = billItems.find((item) => item.ItemId === Existingitem.ItemId + "'")
          if (!ExistingBillItemNoDiscount){
            ExistingBillItemNoDiscount = {
              Quantity : 0,
            }
          }
          if (Existingitem.Quantity >= ExistingBillItem.Quantity 
            + ExistingBillItemNoDiscount.Quantity + 1){
            const discountQty = Existingitem.ItemsOnDiscount
            if (discountQty >= ExistingBillItem.Quantity + 1) { 
              setBillItems((previtems) =>
                previtems.map((item) =>
                  item.ItemId === ExistingBillItem.ItemId
                    ? { ...item, Quantity: item.Quantity + 1 }
                    : item
                )
              );
              toast.success("Item Added Succesfully first",{
                autoClose: 2000,
              });
            } else {
              const findNodiscountOne = billItems.find((item) => Existingitem.ItemId + "'" === item.ItemId)
              if (findNodiscountOne){
                setBillItems((previtems) =>
                  previtems.map((item) =>
                    item.ItemId === ExistingBillItem.ItemId + "'"
                      ? { ...item, Quantity: item.Quantity + 1 }
                      : item
                  )
                );
              } else {
                const BillItem = {
                  ItemId : Existingitem.ItemId + "'",
                  Itemname : Existingitem.Itemname,
                  Quantity : 1,
                  DiscountP: '0%',
                  price : Existingitem.price
                }
                setBillItems([
                  ...billItems,
                  BillItem
                ])
              }
              toast.success("Item Added Succesfully second",{
                autoClose: 2000,
              });
            }
            
          } else {
            toast.error("Not Enough Qty In Inventory" , {
              autoClose : 1000,
            });
          }
        } else {
          let tempItem = {
                ItemId : Existingitem.ItemId,
                Itemname : Existingitem.Itemname,
                Quantity : 1,
                DiscountP: Existingitem.DiscountP ? `${Existingitem.DiscountP}%` : '0%',
                price : Existingitem.price
          }
          setBillItems(prevItems => [...prevItems,tempItem])
          toast.success("Item Added Succesfully third",{
            autoClose: 2000,
          });
        }
  }

All functions gets executed in sequence first < second < third
(Everything works fine by adding the items though input method)
Full code – (https://pastecord.com/ulutifyzub.js)

i tried to see that if the “alreadyAddedbillItems” is even being updated or not
by using a useEffect having a dependency [alreadyAddedbillItems]

useEffect(() => {console.log(updated)},[alreadyAddedbillItems])

When using input method to add items it works fine means it just executed when i added the item for first time, and not if i added the same item again second time

-> Till now i was thinking ok seems like the “alreadyAddedbillItems” is not being updated but when i tried this it actally was being updated means this useeffect was executing but “alreadyAddedbillItems” was still logging empty in second function.

I have no idea why is this happening , please help me out in figuring out what’s the problem if u can
Thank You !

New contributor

Manan Agarwal is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật