Home > Software engineering >  How can get variable value from firebase getDoc() method in react native
How can get variable value from firebase getDoc() method in react native

Time:12-02

I need to use data from firestore and I retrive them by getDoc() as follow

useEffect(async()=>{
    const docRef = doc(db, "users",user.uid );

    const docSnap = await getDoc(docRef);

    if (docSnap.exists()) {
    
   const  data = docSnap.data();
  const  pic = docSnap.data().photo;
     console.log("data is :", data);
     console.log("pic is :", pic);
   } else {
     // doc.data() will be undefined in this case
     console.log("No such document!");
   }
   })

get data as follow

data is : Object {
  "age": "25",
  "displayName": "nmar Bot",
  "gender": "male",
  "id": "2wj8dAF9QXYmAWsqKzDSNlyKzzw1",
  "job": "dr",
  "photo": "https://firebasestorage.googleapis.com/v0/b/meet-332208.appspot.com/o/images/2wj8dAF9QXYmAWsqKzDSNlyKzzw1/profilePicture.jpeg?alt=media&token=ee74dbd1-26e1-4864-9a9a-c7620d37b902",
  "timestamp": Object {
    "nanoseconds": 920000000,
    "seconds": 1638348589,
  },
}

pic is :"https://firebasestorage.googleapis.com/v0/b/meet-332208.appspot.com/o/images/2wj8dAF9QXYmAWsqKzDSNlyKzzw1/profilePicture.jpeg?alt=media&token=ee74dbd1-26e1-4864-9a9a-c7620d37b902"

but how can use this data in this

source = {{uri :pic }}

and how can call each data to display as follow

name is :
age is :
gender is :
photo is :
job is :

can someone help me?

CodePudding user response:

Because the Firebase SDKs are promise-based APIs, you should make use of a useAsyncEffect implementation where possible like @react-hook/async and use-async-effect. This allows you to trim a lot of unnecessary bloat.

The below code sample is commented to explain what each section does, along with any notes regarding what particular lines do.

import {useAsyncEffect} from '@react-hook/async'

/* ... */

const [user, userLoading] = useAuth(); // details of this will depend on what AuthContext you use here

// ===================================
// Getting the data
// ===================================

const { status, error, value: userData } = useAsyncEffect(async () => {
  if (userLoading) throw new Error("loading"); // user session not validated yet
  if (!user) throw new Error("signed-out"); // not signed in

  const docRef = doc(db, "users", user.uid);

  return getDoc(docRef)
    .then((snap) => {
      if (!snap.exists()) throw new Error("not-found"); // document missing
      return snap.data();
    });
}, [user, userLoading]); // rerun when user/userLoading changes

// ===================================
// Handling different result states
// ===================================

// if errored, pass the error's code (for
// firebase errors) or message (for other
// errors) to the switch instead so you
// can handle them by simply adding a
// case to it.
switch (status === "error" ? error.code || error.message : status) { 
  case "loading":
    return null; // hides component
  case "cancelled":
    /* handle cancelled */
    return (<div class="error">Operation cancelled</div>)
  case "not-signed-in":
    /* handle not signed in */
    return (<div class="error">Not signed in</div>)
  case "not-found":
    /* handle document not found */
    return (<div class="error">Profile data not found</div>)
  default:
    /* handle other errors */
    return (
      <div class="error">
        Failed to retrieve data: {error.code || error.message}
      </div>
    );
  case "success":
    // continues below outside switch
}

// ===================================
// Rendering out the completed content
// ===================================

// Here, userData is your document's data and
// you could also use a deconstruction pattern
// to split it up rather than reference it like
// I have:
// const { name, age, gender, pic, job } = userData;

return (<>
  <img src={userData.pic} />
  <p>Name: {userData.name}</p>
  <p>Age: {userData.age}</p>
  <p>Gender: {userData.gender}</p>
  <p>Photo: <a href={userData.pic}>{userData.pic}</a></p>
  <p>Job: {userData.job}</p>
</>)
  • Related