Home > Back-end >  Why data is not showing getting from firebase user in ReactJs?
Why data is not showing getting from firebase user in ReactJs?

Time:08-18

I am getting user data after signin from firebase. I am also printing it on console and it is showing that the data is here. But when I am trying to show it, it is not showing. There is no error also. I checked the element from the browser developer tools and see there the field is empty. I want to show displayName, email, emailVerified.

Here is the image of console that is showing I am getting data:

enter image description here

My code

import React from 'react';
import { getAuth, onAuthStateChanged } from 'firebase/auth';

const Home = () => {
  // get user information
  let displayName, email, emailVerified;

  const auth = getAuth();
  onAuthStateChanged(auth, user => {
    if (user) {
      // User is signed in, see docs for a list of available properties
      // https://firebase.google.com/docs/reference/js/firebase.User
      displayName = user.displayName;
      email = user.email;
      emailVerified = user.emailVerified;
      console.log(user);
    } else {
      // User is signed out
      // ...
    }
  });
  return (
    <div className="container">
      <div className="card w-75 mx-auto bg-warning mt-3">
        <div className="card-body">
          <h5 className="card-title">Name: {displayName}</h5>
          <h5 className="card-title">Email: {email}</h5>
          <h5 className="card-title">Verified: {emailVerified}</h5>
        </div>
      </div>
    </div>
  );
};

export default Home;

Why the data is not showing? How can I show that data?

CodePudding user response:

Those variables will not work that way - you need to use state in your component, see:

To elaborate - in functional components, the context of the function is essentially the render. Defining them at the top of the scope there will be disconnected from where they are set in the onAuthStateChanged callback - the component will have already been rendered with empty values at the point that the callback is called and won't re-render.

React state is what is used to handle this - and will tirgger a render when they change.

This can be done something like:

const [user, setUser] = useState();

onAuthStateChanged(auth, user => {
  if (user) {
    setUser(user);
  } else {
    // User is signed out
    // ...
  }
});

return (
  <div className="container">
    <div className="card w-75 mx-auto bg-warning mt-3">
      <div className="card-body">
        <h5 className="card-title">Name: {user?.displayName}</h5>
        <h5 className="card-title">Email: {user?.email}</h5>
        <h5 className="card-title">Verified: {user?.emailVerified}</h5>
      </div>
    </div>
  </div>
);
  • Related