Home > Net >  Fetch firebase data before rendering react hook
Fetch firebase data before rendering react hook

Time:08-14

I am relatively new to javascript and React and I am helping out with a project. I want to create a profile page for a signed in user with information stored in a firebase real time database. But the component is not rendering and the console shows 'Uncaught TypeError: Cannot read properties of null (reading 'username')'. I surmise it is because the data from the database is not being fetched before rendering. The data exists. The profile hook -

import React, { useEffect,useState } from 'react';
import {useAuth} from '../contexts/AuthContext'
import { getDatabase,ref, onValue} from "firebase/database";


function Profile(){

    const  [userData, setUserData] = useState({});
    const currentUser = useAuth();

    useEffect(()=>{ putData()
    },[])
    
    async function putData(){

    let db =  getDatabase();    
    let refd = ref(db,'users/'  currentUser.currentUser.uid );
    
    onValue(refd, (snapshot) => {
    console.log(snapshot.val());       
    setUserData(snapshot.val());      
    }, 

    (errorObject) => {
    console.log('The read failed: '   errorObject.name);
    })
    }

    return(

        <div>
        <h3>Username : {userData.username}</h3>
        <h3>Institute name : {userData.institute_name}</h3>
        <h3>Accomodation : {userData.accomodation}</h3>
        <h3>Phone no. : {userData.phone}</h3>
        <h3>Email : {userData.email}</h3>
        </div>
     );
}            
export default Profile;

Does the problem lie with the 'onValue' part or with the react part? Firebase documentation is not helping with my current understanding. Any help on how to accomplish this is appreciated.

CodePudding user response:

useEffect(() => {
try {
  //getting previously saved data
  // console.log({ SelectedCaseDetails });
  const getData = async () => {
    const docRef = doc(
      db,
     "here comes your path to your document"
    );
    const docSnap = await getDoc(docRef);
    console.log("data -->", docSnap.data());
    if (docSnap.exists()) {
      setData(docSnap.data());
      setData(() => ({ ...docSnap.data() }));
    }
  };
  getData();
} catch (error) {
  console.log({ error });
}


 }, []);

You just have to run your get data function in useEffect that runs when page is loading

Hope this helps

  • Related