0
import React from 'react';

import { useState, useEffect, useContext } from 'react';
import { auth } from '../../utils/firebase';
import AuthContext from '../../contexts/AuthContext'

//Components
import Navbar from './Navbar';

function Dashboard() {
    const [email, setEmail] = useState("");
    const [uid, setUID] = useState();

      useEffect(() => {
        console.log(auth.currentUser["email"]);
        setEmail(auth.currentUser["email"]);
        console.log(email);
      }, []);

    return (
        <div>
            <Navbar />
            <h1>Dashboard</h1>
        </div>
    );
}

export default Dashboard;

Hello, I am trying to create a program with react where i log in the user with firebase. However, when trying to get the email and uid from the user, I am able to display the data auth.currentUser["email"] when i do console.log(auth.currentUser["email"]) but when i try to set the state setEmail(auth.currentUser["email"]) and console.log(email) console.log doesn't display anything and I won't understand why?? And i need to access the email to get further data from the user so thank you in advance

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Lara Calvo
  • 43
  • 4
  • 1
    React batches the execution of `useEffect` you will not see the change of email in this render. Please move the `console.log` to outside of the `useEffect` to see the change in the next render – tsamridh86 Sep 05 '21 at 03:41

1 Answers1

3

Because state only has new value when component re render. So you should move console.log to useEffect to check the new value when component re-render.

  useEffect(() => {
    console.log(auth.currentUser["email"]);
    setEmail(auth.currentUser["email"]);
  }, []);

useEffect(() => {
  console.log(email);
}, [email]);
Viet
  • 12,133
  • 2
  • 15
  • 21