Home > Net >  How to get value from an object of maps from Firestore
How to get value from an object of maps from Firestore

Time:02-04

This is my database

I want to access each map and their fields induvidually to pass it to a card

I tried the following code


import React, { useEffect, useState } from "react";
import Sidebar from "./Sidebar";
import Navbar from "./Navbar";
import MyStyledCard from "./RequestCard";
import CardList from "./RequestCard";
import { getDoc, doc } from "firebase/firestore";
import { db } from "../firebase";

export default function Requests() {
  const [Data, setData] = useState([]);
  const reg_no = "G2062059";
  let list = [];
  useEffect(() => {
    const fetchData = async () => {
      const docRef = doc(db, "meta", "project-ideas");
      const docSnap = await getDoc(docRef);

      if (docSnap.exists()) {
        console.log("Document data:", docSnap.data());
        setData(docSnap.data());
      } else {
        // doc.data() will be undefined in this case
        console.log("No such document!");
      }
    };
    // Data.map((anObjectMapped, index) => {
    //   console.log(anObjectMapped.name);
    // });
    fetchData();
  }, []);
  return (
    <div className="requests_out">
      <div className="requsts_side">
        <Sidebar />
      </div>
      <div className="requests_main">
        <Navbar />
        <div className="widgets">
          <h2>{Data[reg_no]}</h2>
        </div>
      </div>
    </div>
  );
}

It gives an error like this.

Uncaught Error: Objects are not valid as a React child (found: object with keys {grp_id, pTitle, status, pDescription}). If you meant to render a collection of children, use an array instead.

If i give console.log(Data) it gives an object like this enter image description here.

CodePudding user response:

The fetch is correct, however you are trying to render a javascript object. This is not possible and invalid JSX.

Choose what property inside G2062059 you want to display

Invalid code:

<div className="widgets">
      <h2>{Data[reg_no]}</h2>  <--- THIS IS INVALID JSX
</div>

Valid code: Render a property of an object (string)

<div className="widgets">
      <h2>{Data[reg_no]?.status}</h2>
 </div>
  • Related