firestore get by id code example

Example 1: firestore get id of new document

async function addCity(newCity) {
  const { id } = await db.collection("cities").add(newCity)
  console.log("the new city's id:", id)
}

Example 2: get data from firestore

const [hospitalsDetails, setHospitalsDetails] = useState([])
    useEffect(()=>{
        //load hospitals into hospitalsList
        const hospitals = []
        db.collection('Hospitals').get()
            .then(snapshot => {
                snapshot.docs.forEach(hospital => {
                    let currentID = hospital.id
                    let appObj = { ...hospital.data(), ['id']: currentID }
                    hospitals.push(appObj)

                    hospitals.push(hospital.data())
            })
            setHospitalsDetails(hospitals)
        })
    },[])

Tags:

Misc Example