2

I'm learning these times how to work with Firebase and react Now, I created a "users" collection and add a test doc to it named "one" as I show below. However, When I tried to get this doc I get many data which probably has nothing to do with that doc.

Here I create the doc and take data from it

import { createContext } from "react";
import { db } from "../firebase";

const DbContext = createContext();

export const useDb = () => {
  return useContext(DbContext);
};

export const DbProvider = ({ children }) => {

  //creating "one" doc 
  const uploadToDb = (
    email,
    photo,
    userName,
    gender,
    age,
    phone,
    country,
    city
  ) => {
    return db.collection("users").doc("one").set({
      photo,
      userName,
      gender,
      age,
      phone,
      country,
      city,
    });
  };

  //get data from doc
  const getFromDb = (email) => {
    var dbRef = db.collection("users").doc("one");

    return dbRef.get();
  };

  const value = { uploadToDb, getFromDb };

  return <DbContext.Provider value={value}>{children}</DbContext.Provider>;
};

Here I'm trying to get and print the data Im getting

  useEffect(() => {
    const getDetails = async () => {
      try {
        const res = await getFromDb(currentUser.email);
        console.log("res", res);
      } catch (error) {
        console.error(error);
      }
    };
    getDetails();
  }, []);

The console shows enter image description here

"DB" is the name of firebase/firestore which I export from firebase.js file

Shuki
  • 33
  • 4

1 Answers1

1

Your getFromDb method returns a document snapshot which is what you are printing. If you want to get data inside that object, you need to print as mentioned by @AmitTiwary:

use res.data() to get data from res in console.log("res "+res.data());

which should return a json object according to DocumentSnapshot

Farid Shumbar
  • 1,360
  • 3
  • 10
  • @Wytrzymały Wiktor No. I'm getting back "res undefined" in console... – Shuki Mar 25 '21 at 10:06
  • `res undefined` may occur because your doc `one` doesn’t exist in your Firestore. Try logging it in your `useEffect()` to see if that’s the case. For example: if(res.exists()){ console.log(“Res exists”); }else{ console.log(“Res doesn’t exist”); } – Farid Shumbar Apr 22 '21 at 10:29
  • 1
    @WytrzymałyWiktor Thanks!! I haven't used data as a method – Shuki Aug 14 '21 at 15:03