Home > Mobile >  React SetState to update An Array and save to Firestore
React SetState to update An Array and save to Firestore

Time:03-06

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.

CodePudding user response:

The cart state wont update instantly so you need to use another variable that has your new values for cart (cartArray in this example).

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

   // Add Product to cart 
  const addProduct = (product) => {
  let cartArray= [...cart]
  
const exist = cartArray.find((x) => x.id === product.id);
if (exist) {
  cartArray = cartArray.map((x) =>
      x.id === product.id ? { ...exist, qty: exist.qty   1 } : x
    ) 
  
  setDoc(
    doc(firebaseFirestore, "users", user?.uid!),
    { cart: cartArray },
    { merge: true }
  )
    .then(() => {console.log("done") ; setCart([...cartArray]) })
    .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 {
  cartArray = [...cart, { ...product, qty: 1 }];
  setDoc(
    doc(firebaseFirestore, "users", user?.uid!),
    { cart: arrayUnion(...cartArray) },
    { merge: true }
  )
    .then(() => { console.log("done") ; setCart([...cartArray]) })
    .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"));
}
 };
  • Related