Home > Enterprise >  How can I return empty the snapshot docs of firebase without returning undefined
How can I return empty the snapshot docs of firebase without returning undefined

Time:10-27

So I just directly go to the code. Basically let say I have a carts and orders...The carts and orders should be in the item of a certain "email". Now what I want to do since my snapshot carts and orders loop around its item and some of its email is not the same whose email is login. I wonder how can I return empty the carts and orders if the login account has no yet "carts or orders" without returning "undefined" item.

onSnapshot(orderCollectionRef,snapshot => {
  // snapshot.docs.map((doc_,idx) => {
  //   if (doc_.data().email == currentUser?.email) {
  //     setOrders(prevState => [...prevState,doc_.data()])
  //   }
  // })
  setOrders(snapshot.docs.map((doc_,idx) => {
    if (doc_.data().email == currentUser?.email) {
      return {
        ...doc_.data()
      }
    } else {
      return null 
    }
  }))
})

As you see I have a doc_.data().email == currentUser?.email because it is inside the authentication email...now since the orders have different located emails in their cart.. I wonder how to not make const [orders,setOrders] = useState([]) not have a list of undefined cause this is what returning at when their is no user login or there is no item in orders and carts... You see also in the comment tags that those are most valid that do not return undefined since it was a push array,but it was not useful cause it is not removing the arrays when I update new carts rather it just make the call twice...basically what I mean here( I am talking too much) is

setOrders(snapshot.docs.map((doc_,idx) => {
  if (doc_.data().email == currentUser?.email) {
    return {
      ...doc_.data()
    }
  } else {
    // What should will return here???
    // return null 
  }
}))

How do I make this return just empty just none if there is no email that in the list of snapshot of carts and orders

CodePudding user response:

It sounds like you want to filter out the items without a matching email address, and then only map the remaining ones, which you can do with Array.filter:

setOrders(snapshot.docs
  .filter((doc_) => doc_.data().email == currentUser?.email)
  .map((doc_) => doc_.data());
}))
  • Related