1

I'm making an eccomerce web app using next13 and firebase, I want my cart component to be visible when shoppingCart.length>0 Here's my code for Cart.jsx:


"use client"
import React, {useState, useEffect} from 'react'
.
.
.
import { getDoc, doc,  onSnapshot } from 'firebase/firestore'

const Cart = () => {
    const router = useRouter();
    const [user, setUser] = useState({});
    const [items, setItems] = useState(0);
    const [visible, setVisible] = useState(false);
    const { currentUser } = useAuth();

    useEffect(() => {
      const userUpdate = () => {
        if (currentUser) {
        setUser(currentUser);
       } }
      const userRef = doc(db, "users", user.uid)
      const unsub = onSnapshot(userRef, (user)=> {
        console.log("User: ", user.data());
        setItems(user.data().shoppingCart.length)
        setVisible(user.data().shoppingCart.length>0)
      })
    return ()=>{
      userUpdate();
      unsub();
    };
    });

    const clickHandler =  (e) => {
        e.preventDefault();
        router.push('/ShoppingCart');
    };
  return (
<>
{(currentUser && visible)?<button onClick={clickHandler} className='CartButton'><span className="ItemCount">{items}</span><Image src={CartImage} alt="Cart-Image" height={40} width={40}></Image></button>:null}
</>    
  )
}

export default Cart

But I get this error: enter image description here

I'm importing { db } correctly in other components where I was required to get data from database I used db the same way by using userRef = doc(db, "users", user.uid) and it works there.

Jonas
  • 121,568
  • 97
  • 310
  • 388

0 Answers0