Click here to Skip to main content
15,868,164 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
So, I'm able to create an account and to successfully get to the MyAccount page, see who's currently logged in to MyAccount page and log out of the MyAccount page (MyAccount.js).
However, when I try to log in using an email + password by pressing the Sign In button of the Body2.js, I can reach the MyAccount page but can't see who's logged in and I get the "User already Logged In!" error message.

My firebase file:

// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import { createUserWithEmailAndPassword, getAuth, onAuthStateChanged, signOut, signInWithEmailAndPassword } from "firebase/auth";
import { useEffect, useState } from "react";


// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries

// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
  apiKey: "AIzaSyA7JlUvGBqA7kGEvqLSsWs9kdfufMvJw4U",
  authDomain: "teslaclone-b61cc.firebaseapp.com",
  projectId: "teslaclone-b61cc",
  storageBucket: "teslaclone-b61cc.appspot.com",
  messagingSenderId: "938981674626",
  appId: "1:938981674626:web:59262207c001c577236e9b",
  measurementId: "G-TWPZ2229F3"
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);

const auth = getAuth(app);

export function signup(email, password) {
  return createUserWithEmailAndPassword(auth, email, password);
}


export function logout() {
  return signOut(auth);
}


export function login(email, password) {
  return signInWithEmailAndPassword(auth, email, password);
}


// Custom Hook

export function useAuth() {
  const [ currentUser, setCurrentUser ] = useState();
  useEffect(() => {
    const unsub = onAuthStateChanged(auth, user => setCurrentUser(user));
    return unsub;
  }, [])
  return currentUser;
}



My App.js file:

import React, { useState } from 'react';
import './App.css';
import Header from './Header';
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';
import Menu from './Menu';
import HeaderBlock from './HeaderBlock';

import Header2 from './Header2';
import Body2 from './Body2';
import Footer2 from './Footer2';

import SignUp from './SignUp';
import MyAccount from './MyAccount' ;


function App() {

  const [isMenuOpen, setIsMenuOpen] = useState(false);


  return (

    
    <Router>
      <div className="app">

        <Switch> 

            <Route exact path='/'>

              <Header isMenuOpen={isMenuOpen} setIsMenuOpen={setIsMenuOpen}/>

              {isMenuOpen && <Menu/>}

              <HeaderBlock />

            </Route>



            <Route exact path='/Login2'>

              <Header2 />

              <Body2 />
          
              <Footer2 />

            </Route>



            <Route exact path='/signup'>

              <Header2 />

              <SignUp />

              <Footer2 />
          

            </Route>


            <Route exact path='/MyAccount'>

              <Header2 />

              <MyAccount />
          
              <Footer2 />

            </Route>


        </Switch>

      </div>
    </Router>

  );
}

export default App;



My SignUp.js file:

import './SignUp.css';
import React, { useState, useRef } from 'react';
import { useHistory } from 'react-router-dom';
import { signup, useAuth } from './firebase';


function SignUp() {

  const history = useHistory();

  const emailRef = useRef();
  const passwordRef = useRef();

  const [ loading, setLoading ] = useState(false);

  const currentUser = useAuth();

  async function handleSignup() {
    
    setLoading(true);
    try {
        await signup(emailRef.current.value, passwordRef.current.value);
    }
    catch {
      alert("Account already created/Credentials already used");
    }
    setLoading(false);
};




  return (
    <div className='signup'>

        <div className='signup__info'>
                
                <h1> Account Creation </h1>

                <form className='signup__form'>

                    <label htmlFor='email'> Email Address </label>
                    <input 
                        ref={emailRef}
                        placeholder=''
                    />

                    <label htmlFor='email'> Password </label>
                    <input 
                        ref={passwordRef}
                        type="password"
                         placeholder=""
                    />

                    <div className='signupblock__actions'>
                        <button 
                            className='signupblock__buttonPrimary' 
                            disabled={ loading || currentUser }
                            onClick={() => {handleSignup(); history.push('/MyAccount');}}> Register </button>

                            <div className='signupblock__divider'>
                                <hr/> <span> OR </span> <hr/>
                            </div>
                            
                        <button
                             className='signupblock__buttonSecondary'
                             onClick={() => {history.push('/');}}> Home </button>
                    </div>

                </form>

            </div>

    </div>
  );
};

export default SignUp;



My Body2.js file:

import React, { useState, useRef } from 'react';
import { useHistory } from 'react-router-dom';
import './Body2.css';
import { useAuth, login } from './firebase';



function Body2() {

  const history = useHistory()
  
  const currentUser = useAuth();

  const [ loading, setLoading ] = useState(false);

  const emailRef = useRef();
  const passwordRef = useRef();

  async function handleLogin() {
    
    setLoading(true);
    try {
        await login(emailRef.current.value, passwordRef.current.value);
    }
    catch {
      alert("User already Logged In!");
    }
    setLoading(false);
};


  return (
    <div className='body2'>

        <div className='login2__info'>
                
                <h1> Sign In </h1>

                <form className='login2__form'>

                    <label htmlFor='email'> Email Address </label>
                    <input 
                        type='email'
                         id='email'
                    />

                    <label htmlFor='email'> Password </label>
                    <input 
                        type='password'
                         id='password'
                        
                    />

                    <div className='headerBlock2__actions'>
                        <button 
                            className='headerBlock2__buttonPrimary' 
                            disabled={ loading || currentUser }
                            onClick={() => {handleLogin(); history.push('/MyAccount');}} > Sign In </button>

                            <div className='login2__divider'>
                                <hr/> <span> OR </span> <hr/>
                            </div>
                            
                        <button
                             className='headerBlock2__buttonSecondary'
                             onClick={() => {history.push('/signup');}}> Create Account </button>
                    </div>




                </form>


            </div>

    </div>
  )
}

export default Body2;



MyAccount.js file:

import React, { useState } from 'react';
// import app from './firebase';
import './MyAccount.css';
import { logout, useAuth } from './firebase';
import { useHistory } from 'react-router-dom';

function Home() {

  const history = useHistory();

  const currentUser = useAuth();


  const [ loading, setLoading ] = useState(false);

  async function handleLogOut() {
    setLoading(true);
    try {
      await logout();
    }
    catch {
      alert("Couldn't Log Out Effectively");
    }
    setLoading(false);
  }

  return (
    <div>
        <h1> Home </h1>
        <p> What's Up Everyone! </p>
        
        <h2> Currently logged in as: { currentUser?.email } </h2>
        <button 
          disabled={ loading }
          onClick={() => {handleLogOut(); history.push('/');}}> Log Out </button>
    </div>
  );
}

export default Home;


What I have tried:

I think I'm not resetting the current user value in Body2.js but I'm not sure or don't know how to.
Posted
Updated 20-Dec-22 8:07am

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900