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..
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)
}
