'React SetState to update An Array and save to Firestore

I working on an e-commerce site, where I have a cart array

const [cart, setCart] = useState([]);

// Add Product to cart
  const addProduct = (product) => {
    const exist = cart.find((x) => x.id === product.id);
    if (exist) {
      setCart(
        cart.map((x) =>
          x.id === product.id ? { ...exist, qty: exist.qty + 1 } : x
        )
      );
      setDoc(
        doc(firebaseFirestore, "users", user?.uid!),
        { cart: cart },
        { merge: true }
      )
        .then(() => console.log("done"))
        .catch((error) => console.log("Error"));
      localStorage.setItem("cart", JSON.stringify(cart));
      chakraToast({
        status: "success",
        title: `Product updated with a new quantity`,
        isClosable: true,
        containerStyle: {
          fontSize: "12.5px",
        },
        variant: "subtle",
        position: "bottom-right",
      });
    } else {
      setCart([...cart, { ...product, qty: 1 }]);
      setDoc(
        doc(firebaseFirestore, "users", user?.uid!),
        { cart: arrayUnion(...cart) },
        { merge: true }
      )
        .then(() => console.log("done"))
        .catch((error) => console.log("Error"));
      chakraToast({
        status: "success",
        title: "Product added successfully",
        isClosable: true,
        containerStyle: {
          fontSize: "12.5px",
        },
        variant: "subtle",
        position: "bottom-right",
      });
      console.log("Cart First Instance", cart);
      console.log(localStorage.getItem("cart"));
    }
  };

The AddProduct function adds objects to the cart Array... The object added must be saved in Firestore DB. On the first click of the button, it sends an empty Array to firestore, because the cart is empty. On the second Click, it sends the First object. On Subsequent clicks, it like it's one step backward.

I also did this

 useEffect(() => {
    localStorage.setItem("cart", JSON.stringify(cart));
    JSON.parse(localStorage.getItem("cart")!);
    console.log(cart);
  }, [cart]);

Question: How do I get the cart value on the First Click and save it to firestore.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source