Home > database >  Query to get an array item where equals to email react js firebase
Query to get an array item where equals to email react js firebase

Time:07-06

I have a problem when i tried to get a query with filter data for a specific user logged in. I need to get the items collection for user logged, but the query list all orders

const auth = getAuth(app);

const user = auth.currentUser.email;

const {buyer} = useParams();

useEffect( () =>{
    const ordersRef = collection(db, "orders")
    const q = buyer ? query(ordersRef, where("buyer", "array-contains", user.toString())): ordersRef
    getDocs(q)
        .then((resp) => {
            const newOrders = resp.docs.map((doc) => {
                return {
                    id: doc.id,
                    ...doc.data(q)

                }
            })
            setItems(newOrders)
            console.log(newOrders)
        })
},[user, buyer])

firebase-database

Anyone can help me?

CodePudding user response:

EDIT: Explanation You can query object directly using buyer.email, array-contains help you if the buyer was an array of object.

Can you try the below code

const auth = getAuth(app);

const user = auth.currentUser.email;

const {buyer} = useParams();

useEffect( () =>{
    const ordersRef = collection(db, "orders")
    const q = buyer ? query(ordersRef, where("buyer.email", "==", user.toString())): ordersRef
    getDocs(q)
        .then((resp) => {
            const newOrders = resp.docs.map((doc) => {
                return {
                    id: doc.id,
                    ...doc.data(q)

                }
            })
            setItems(newOrders)
            console.log(newOrders)
        })
},[user, buyer])

CodePudding user response:

const auth = getAuth(app);

const user = auth.currentUser.email;

const {buyer} = useParams();

useEffect( () =>{
    const ordersRef = collection(db, "orders")
    const q = buyer ? query(ordersRef, where(buyer.email, "array-contains", buyer)): ordersRef
    getDocs(q)
        .then((resp) => {
            const newOrders = resp.docs.map((doc) => {
                return {
                    id: doc.id,
                    ...doc.data(q)

                }
            })
            setItems(newOrders)
            console.log(newOrders)
        })
},[user, buyer])

I tried with this update but i get the same result. The console show me all orders, not a specific orders from user. Maybe the problem is in the query?

  • Related