Ad

React Firebase 9 How To Delete Current User Account?

I'm doing a react base app that logs the user in with firebase auth. Everything there works fine, but now I want to allow the user to delete their account if the wish, but I'm not sure how to do it. I tried what was in the firebase documentacion but I get that I need to reauthenticate the user before as a matter of security, and I couldn't find tutorials of how to use the reauthenticateWithCredential() function.

Here is my profile code, a modal appears as a warming before the user deletes the account and then it calls a function in my firebase file. Since it appears that I need the user to write their password again there is a form in the modal that sends it to the function.

import { Fragment, useEffect, useState } from "react";
import { useRouter } from "next/router";
import { onSnapshot, query, where  } from 'firebase/firestore';
import { useAuth } from "../../auth/authUserProvider";
import { usersColRef, deleteSignedUser, auth } from "../../firebase";
import styles from "../profileRender/profileRender.module.scss";
import Modal from "react-bootstrap/Modal";

const Profile = ({queryUserId}) => {
    const router = useRouter();
    
    const { authUser, loading } = useAuth();
    const [userId, setUserId] = useState("");
    const [showModal, setShowModal] = useState(false);
    const [isUser, setIsUser] = useState(false);
    const [isLoading, setIsLoading] = useState(true);
    const [profileCreated, setProfileCreated] = useState(false);
    const [userProfile, setUserProfile] = useState({
            "userId" : "",
            "username" : "",
            "userDescription" : "",
            "profilePicture" : ""
    });


    useEffect(() => {
      //here i get the user profile info from firebase

    }, [queryUserId ,userId, authUser, profileCreated, authUser]);

    const renderEdit = () => {router.push("/profile/edit");}
    const handleOpenModal = () => {setShowModal(true)};
    const handleCloseModal = () => {setShowModal(false)};
    const deleteUser = (e) => {
        e.preventDefault();
        deleteSignedUser(e.target[0].value);
    }

    const ProfileRender = () => {
        if(profileCreated === false){
            if(isLoading === true){
                return (
                    <div className="page-background-setted-height">
                        <p>Loading...</p>
                    </div>
                    
                )
            } else {
                return (
                    <div className="page-background-setted-height">
                        <span className={styles.profile__title}>My profile</span> 
                        <hr className={styles.profile__title__hr}></hr>
                        <div className={styles.profile__createAcount}>
                            <h3 className={styles.profile__createAcount__item}>Create your profile</h3>
                            <button onClick={renderEdit} className={`btn btn-dark ${styles.profile__createAcount__item}`}>Create</button>  
                        </div>
                    </div>
                )
            }
            
        } else {
            if(isLoading === true){
                return (
                    <div className="page-background-setted-height">
                        <p>Loading</p>
                    </div>
                    
                )
            } else {
                return(
                    <div className="page-background">
                        <div className={styles.profile}>
                        <span className={styles.profile__title}>My profile</span> 
                        <hr className={styles.profile__title__hr}></hr>
                            <div className={styles.profile__top}>
                                <img className="" src={userProfile.profilePicture}/>
                                <div className={styles.profile__top__name}>
                                    <div><h3>{userProfile.username}</h3></div>
                                </div> 
                            </div>
                            <h4>About me...</h4>
                            <h6>{userProfile.userDescription}</h6>
                            {isUser && 
                            <div className={styles.profile__actions}>
                                <button onClick={renderEdit} className="btn btn-dark">Edit profile</button>
                                <button type="button" onClick={handleOpenModal} className="btn btn-danger">Delete profile</button>
                            </div>
                            }
                        </div>
                        ///the modal element
                        <div>
                        <Modal show={showModal} onHide={handleCloseModal}>
                          <Modal.Header closeButton>
                            <Modal.Title>Are you sure?</Modal.Title>
                          </Modal.Header>
                        <Modal.Body>
                          <h3>Once you delete your profile, all your blogs will be deleted permanently.</h3>
                          <h5>In order to continue, please write your password again</h5>
                          <form onSubmit={deleteUser}>
                              <label>Password</label>
                              <input type="password"/>
                              <button type="submit" className="btn btn-danger">Delete profile</button>
                          </form>
                        </Modal.Body>
                          <Modal.Footer>
                            <button className="btn btn-primary" onClick={handleCloseModal}>
                              No, thanks
                            </button>
                          </Modal.Footer>
                        </Modal>
                        </div>
                    </div>
                )
            }  
        }
    }

    return (
        <Fragment>
        <ProfileRender />
        </Fragment>
    )
}



export default Profile;

And here is the function I call from firebase.

import { initializeApp } from "firebase/app";
import { 
  getAuth, 
  createUserWithEmailAndPassword,  
  signOut,
  signInWithEmailAndPassword,
  deleteUser,
  EmailAuthProvider,
  userProvidedPassword,
  reauthenticateWithCredential
} from "firebase/auth";
import { getStorage } from "firebase/storage";
import {getFirestore, collection, addDoc, deleteDoc, doc, updateDoc } from 'firebase/firestore';


const firebaseConfig = {...};
initializeApp(firebaseConfig);
const db = getFirestore();

const auth = getAuth();

const storage = getStorage();

let user;

///AUTH FUNCTIONS

const createAccount = (values) => {
  createUserWithEmailAndPassword(auth, values.email, values.password)
  .then((cred) => {
    user = cred.user;
    localStorage.setItem("user", cred.user.uid);
  })
  .catch(err => {
    console.log(err.message)
  
  })
}

const signUserOut = () => {
  signOut(auth)
  .then(() => {
    user = "";
  })
  .catch((err) => {
    console.log(err)
  })
};

const signUserIn = (values) => {
  signInWithEmailAndPassword(auth, values.email, values.password)
  .then((cred) => {
    user = cred.user;
    localStorage.setItem("user", cred.user.uid);
    
  })
  .catch((err) => {
  })
};

const deleteSignedUser = async (password) => {
  const   = EmailAuthProvider.credential(
    auth.currentUser.email,
    password
    )
  const result = await reauthenticateWithCredential(
    auth.currentUser, 
    credential
    ) 
    deleteUser(result).then(() => {
      console.log("success in deleting")
      localStorage.removeItem("user");
  }).catch(err => console.log(err));  */
}

When I run this code I get this error:

TypeError: (0 , firebase_util__WEBPACK_IMPORTED_MODULE_0_.getModularInstance)(...).delete is not a function

Can someone help me with this?

Ad

Answer

The reauthenticateWithCredential() returns UserCredential but deleteUser() takes User as parameter. Try refactoring as shown below:

const deleteSignedUser = async (password) => {
  const credential = EmailAuthProvider.credential(
    auth.currentUser.email,
    password
  )

  const result = await reauthenticateWithCredential(
    auth.currentUser,
    credential
  )

  // Pass result.user here
  await deleteUser(result.user)
 
  console.log("success in deleting")
  localStorage.removeItem("user");
}
Ad
source: stackoverflow.com
Ad