Home > Software design >  How can I successfully loop this Boolean to output a product with less than color quantity?
How can I successfully loop this Boolean to output a product with less than color quantity?

Time:03-27

This is my firestore with its following data. I want my code to check if the colorMap which is the color quantity then output the prodName which is the product with less than 10 color quantity.

Firestore

And this is the error that I'm getting in my code.

error

This is the code. I'm not sure if the .filter is actually working.

{details.filter(details => details.color < 10).map((val) => {
        return (<ul>
                <li key={val.id}><p className="pt-2">{val.prodName} </p></li>
                </ul>
        );

      })}

This is my reference for getting the data in the firebase.

  const [details, setDetails] = useState([]);

  const userData = async () => {
  
  const q = query(collection(db, "products"));

  const querySnapshot = await getDocs(q);
  const data = querySnapshot.docs.map((doc) => ({
    ...doc.data(),
    id: doc.id,
  }));
  setDetails(data);
};

If you guys know how to do this with using the if statement. Please refer it to me. Thanks.

CodePudding user response:

The 2nd parameter in map() is the index of element and not an object. Try using the document ID as the key instead:

key={val.id} // instead of {item.id}  

Also you should create 1 list and then add list items using map instead of creating a new list for each item:

<ul>
{details.filter((detail) => Object.values(detail.colorMap).find(c => c < 10)).map((val, item) => {
        return (<li key={val.id}><p className="pt-2">{val.prodName} </p></li>);
})}
</ul>
  • Related