T. Karter
T. Karter

Reputation: 738

How to get document id of firestore in React

This is my firestore database: enter image description here After useEffect() updated the workouts const, I have access to name and uId only. How can I have access to the document id as well?

import React, { useState, useEffect } from "react";
import "./Workouts.sass";
import Workout from "./Workout";
import firebase from "./firebase";

function Workouts() {
  const [workouts, setWorkouts] = useState([]);

  useEffect(() => {
    let user = firebase.auth().currentUser;
    const database = firebase.firestore();
    const unsubscribe = database
      .collection("workouts")
      .where("uId", "==", user.uid)
      .onSnapshot((snapshot) => {
        setWorkouts(snapshot.docs.map((doc) => doc.data()));
      });

    return () => {
      unsubscribe();
    };
  }, []);

  return (
    <div className="Workouts">
      {workouts.map((workout) => (
        <Workout key={workout.name} workout={workout} />
      ))}
    </div>
  );
}

export default Workouts;

Upvotes: 5

Views: 9181

Answers (1)

Louis Coulet
Louis Coulet

Reputation: 4641

You can use the snapshot doc.id
I like to add id as a property to the object:

snapshot.docs.map((doc) => ({id: doc.id, ...doc.data()}))

Upvotes: 12

Related Questions