-1

so im adding users to firestore as well as in authentication but doing this actually replaces the current user with that email which i dont want this as in the image after adding teacher the logged in account is replaced by added account i think its the useEffect which is doing this.here is dashboard where the useEffect is showing the current account logged in

Add user.js

    const [data, setData] = useState({});
      const handleinput = e =>{
        const id = e.target.id;
        const value = e.target.value;
      
        setData({...data, [id]:value})
      }
      console.log(data)
    
      
      const handleadd = async (e) =>{
        e.preventDefault();
        try{
          const res = await createUserWithEmailAndPassword(
            auth,
            data.email,
            data.password
          )
          setDoc(doc(db, "Teachers", res.user.uid), {
            ...data,
            timestamp: serverTimestamp(),
            
          });
        } catch (e){
          alert("Faculty added succesfully")
          console.log(e.message)
        }
      }

authcontext

import { createUserWithEmailAndPassword, onAuthStateChanged, signOut, signInWithEmailAndPassword, signInWithPopup } from 'firebase/auth'
import React, {
  createContext, 
  useContext, 
  useState, 
  useEffect} from 'react'
import { auth } from '../../firebase'

const AuthContext = createContext();

export const AuthProvider = ({children}) => {

  const userIn = ( email, password) =>{
    return signInWithEmailAndPassword(auth, email, password)
  }

  //sign up context
  const [user, setUser] = useState({})
  const addusers = (email, password) => {
    return createUserWithEmailAndPassword(auth, email, password);
  }
  
  useEffect(()=>{
    const unsubscribe = onAuthStateChanged(auth, (currentUser) =>{
      console.log(currentUser);
      setUser(currentUser)
    })
    return () =>{
      unsubscribe()
    }
  },[])

  //logout
  const logout =() =>{
    return signOut(auth)
  }





  return (
    <AuthContext.Provider value={{addusers, user, logout, userIn  }}>
      {children}
    </AuthContext.Provider>
  )
}

export const UserAuth =()=>{
  return useContext(AuthContext)
}

1 Answers1

1

By using the JS SDK createUserWithEmailAndPassword() method the newly created user is automatically signed in when the method call is successful. You cannot prevent that.

The classical approach in your case is to use a Cloud Function to create the user, because Cloud Functions use the Admin SDK which allows creating users in the back-end without signing them in from the front-end.

You’ll find an example of this approach in the following article: How to create an Admin module for managing Firebase users access and roles.

Renaud Tarnec
  • 79,263
  • 10
  • 95
  • 121