0

how do you find a document by its ID in react?

I'm trying to get each of the document specific ids in my collection in Firestore, but I can't find a way to do it so I can access the properties in the collection so I can properly render my components

[ItemDetailContainer.js]

import React, { useState, useEffect } from "react";
import { useParams } from "react-router-dom";
import ItemDetail from "../ItemDetail/ItemDetail";
import { PRODUCTS } from "../ItemListContainer/Products";
import Spinner from "../ItemListContainer/Spinner";
import firebase, { db } from "../../index";
import { getDoc, doc, addDoc } from "firebase/firestore";

const ItemDetailContainer = () => {
  const [jackets, setJackets] = useState([]);
  const [producto, setProducto] = useState({});
  const { id } = useParams();

  useEffect(() => {
    const singleItem = doc(db, "Products", "YPQGY4euFdaUcCoDm06C");

    getDoc(singleItem).then((rta) => {
      console.log(rta.data());
      console.log(rta.id);

      setProducto({ ...rta.data(), id: rta.id });
    });
  }, []);

  console.log(producto);

  return (
    <>
      <div>
        {producto.id ? (
          <>
            <ItemDetail producto={producto} />
          </>
        ) : (
          <div>
            <Spinner />
          </div>
        )}
      </div>
    
    </>
  );
};

export default ItemDetailContainer;
Dharmaraj
  • 47,845
  • 8
  • 52
  • 84
Nacho
  • 41
  • 6
  • Where are the multiple IDs coming from? Can you share that code along with a screenshot of your Firestore database? – Dharmaraj Apr 22 '22 at 10:43

1 Answers1

1

You can use in operator in a query that combines up to 10 equality (==) clauses on the same field with a logical OR and then use getDocs() to get all matching documents:

import { query, where, collection, documentId } from "firebase/firestore";

const colRef = collection(db, "Products");
const q = query(colRef, where(documentId(), 'in', ['docId1', 'docId2']));

getDocs(q).then((snap) => {
  console.log(snap.docs.map(d => ({ id: d.id, ...d.data() }))
})

If you have an array of more than 10 IDs then you can individually query the documents.

Dharmaraj
  • 47,845
  • 8
  • 52
  • 84