Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Display Firestore Data with a datatype of map: Error: Objects are not valid as a React child

Retrieving from firestore:

const [product, setProduct] = useState([]);

  const getProducts = async () => {
    const querySnapshot = await getDocs(collection(db, "products"));
    const arr = [];
    querySnapshot.forEach((doc) => {
      arr.push({
        ...doc.data(),
        id: doc.id,
      });
    });
    setProduct(arr);
  };

  useEffect(() => {
    getProducts();
  }, []);

I have this colorMap retrieved from Firestore:

export const data = [
  {
    colorMap: { red: 6, blue: 7, green: 8 },
    id: "a4TK38mByQbim4TwOHMY"
  },
  
  {
    colorMap: { Black: 20, Gold: 10 },
    id: "m08YmrlFxhxLxyc3hVjT"
  },
  {
    colorMap: { green: 9, red: 19 },
    id: "nN2w57SiDovbtQ6EBzGb"
  }
];

How can I display it in the screen?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 {product &&
        product.map((index) => (
          <>
            <b>{index.prodName + "-" + index.size + index.cat}</b>
            <li>{index.id}</li>
          </>
        ))}

If I’ll add this:

<li>{index.colorMap}</li>

It will cause an error:

Uncaught (in promise) Error: Objects are not valid as a React child
(found: object with keys {green, red, blue})

How do I resolve this? Any help would be appreciated. Thank you

>Solution :

You can use Object.entries() and then map those items as shown below:

{product &&
  product.map((index) => (
  <div>
    <b>{index.prodName + "-" + index.size + index.cat}</b>
    <p>{index.id}</p>
    <ul>
      {
        Object.entries(index.colorMap).map((color) => (
          <li>{color[0]} - {color[1]}</li>
        ))
      }
    </ul>
  </div>
))}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading