Home > Software design >  get a value from firestore array contains
get a value from firestore array contains

Time:11-08

i can only get the values i need from the array if i added string such "اقلام", "سبورة" or any other string value, however i want the value to be passed a an prop from another component or screen. is there away to handle this issue.

enter image description here

const fetchCategoryProducts = (catId)=>{
    const categoryProductsCollection = query(collection(db, "Product"), where("categories", "array-contains", catId))
    const getCategoryProducts = getDocs(categoryProductsCollection);
    const categoryProducts = (await getCategoryProducts).docs.map(item=>{
        const data = item.data();
        data.id = item.id;
        return data
    })
    console.log(categoryProducts) // getting empty array here
}}

CodePudding user response:

According to my question:

What is the value of catId?

And your answer:

The value of the string is one of the values included in the array. I tested it with just a string instead of the catId, and it works fin, but when I pass the catId from other components I get an empty array.

If the code works with the hardcoded value, then most likely the value in the database contains some white spaces and for that, you have to use trim():

const fetchCategoryProducts = (catId)=>{
    const categoryProductsCollection = query(collection(db, "Product"), where("categories", "array-contains", catId.trim()))
    const getCategoryProducts = getDocs(categoryProductsCollection);
    const categoryProducts = (await getCategoryProducts).docs.map(item=>{
        const data = item.data();
        data.id = item.id;
        return data
    })
    console.log(categoryProducts)
}}
  • Related