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

How to fetch id from console log firestore and react js

fam, I have a document added to cloud firestore, I can successfully read data from the database, I want to get only the ID from the document, here’s the code snippet:-

  const [tasks, setTasks] = useState([]);
  const [fetch, setFetch] = useState({
    id: "",
  });

  const {userId} = useParams();
  
  const collectionRef = collection(db, "microsystems/" + userId , "reportmcs")

  useEffect(()=>{ 
    const getTasks = async () => {
      const q = query(collectionRef)
      await getDocs(q).then((task)=>{
       let tasksData = task.docs.map((doc) => ({...doc.data(),
      id: doc.id}))
      setTasks(tasksData)
      setFetch(tasksData)
      console.log("fetchData", tasksData)
      console.log("taskData", tasksData)
      }).catch((err) =>{
        console.log(err)
      })
    }
    getTasks()
  }, [])

  let sampleId = fetch.id
    console.log("currentvalue from doc", sampleId)
    

What I tried to do was that in the code snippet above, I have two states above, the second state, that is (fetch), I’m currently using that to get the id for that particular document, I can see all the fields in the document in my console log but when I try to get only the id, it returns undefined..

Here’s my console log:-
enter image description here

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

How can I target only that id and view in my console log???

>Solution :

If your query returns only 1 document then you can just read first item in that array as shown below or alternatively maps a new array of IDs if there are many documents. Try:

const getTasks = async () => {
    const q = query(collectionRef)

    const snapshot = await getDocs(q)
    const tasksData = task.docs.map((doc) => ({
        ...doc.data(),
        id: doc.id
    }))
    
    console.log(tasksData[0].id)
  
    // in case of multiple documents
    console.log(tasksData.map(task => task.id))

    setTasks(tasksData)
    setFetch(tasksData)
    console.log("fetchData", tasksData)
    console.log("taskData", tasksData)
}
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