最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get document id of firestore in React - Stack Overflow

programmeradmin2浏览0评论

This is my firestore database: 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;

This is my firestore database: 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;

Share Improve this question asked Aug 31, 2020 at 12:55 T. KarterT. Karter 7388 silver badges32 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 12

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()}))
发布评论

评论列表(0)

  1. 暂无评论