3

I have created a new form after creating a user with phone number authentication(in firebase), But an error keeps on coming after submitting FirebaseError: Firebase: Error (auth/user-token-expired) The Error is Comming in this code

//This Component is used to store the Name ,Phone Number Of new User  Which have Registered in SignUp With Number
import "./Auth.scss";
import React, { useState } from "react";
import { updateProfile, updateEmail } from "firebase/auth";
import { auth } from "../../firebase/config";
import { useNavigate, useLocation } from "react-router";
import usePhoneSignUp from "../../hooks/usePhoneSignUp";
import { update } from "lodash";

const SaveUserDetails = () => {
  //code to extract userType after navigating from SignUpWithNumber page
  const { state } = useLocation();
  const userType = state.userType;
  console.log(userType);

  // .......
  const {
    signUp,
    error: signupError,
    isPending: signupIsPending,
  } = usePhoneSignUp();

  const [name, setname] = useState();
  const [email, setemail] = useState();
  const navigate = useNavigate();
  const handleChange = (e) => {
    e.preventDefault();
    const { name, value } = e.target;
    switch (name) {
      case "displayname":
        setname(value);
        break;
      case "email":
        setemail(value);
        break;
      default:
        break;
    }
  };
  const updateEmailUser = () => {
    updateEmail(auth.currentUser, email)
      .then(() => {
        // Email updated!
        // ...
        console.log("email Updated");
      })
      .catch((error) => {
        // An error occurred
        console.log("email Updated");

        // ...
        console.log(error);
      });
  };
  const updateUserProfile = () => {
    updateProfile(auth.currentUser, {
      displayName: name,
    })
      .then(() => {
        console.log("profile Updated" + name + " " + email);
      })
      .catch((error) => {
        console.log(error + "In update profile");
      });
    updateEmailUser();
  };
  const handleSubmit = () => {
    // updateEmailUser();
    updateUserProfile();
    signUp(name, userType, email);
    let path =
      userType === "salonOwner" ? "/addBuisnessDetails" : "/salonsNearby";
    if (signupError) {
      console.log(signupError.message);
    }
    return navigate(path, { replace: true });
  };

  //query function for saloon

  return (
    <>
      <div className="form-wrapper ">
        <div id="register-form">
          <p className="login-title register-title">Complete Your Profile</p>
          <div className="login-hr" />

          <form onSubmit={handleSubmit}>
            <div className="form-group login-sj">
              <label htmlFor="exampleInputName1">Name:</label>
              <input
                type="text"
                className="form-control"
                id="exampleInputName1"
                aria-describedby="emailHelp"
                placeholder="Your Name"
                name="displayname"
                onChange={handleChange}
              />
            </div>
            <div className="form-group login-sj">
              <label htmlFor="exampleInputEmail2">Email address</label>
              <input
                type="email"
                className="form-control"
                id="exampleInputEmail2"
                aria-describedby="emailHelp"
                placeholder="Enter email"
                name="email"
                onChange={handleChange}
              />
            </div>
            {/* <div className="form-group login-sj">
            <label htmlFor="exampleInputPassword1"></label>
            <input
              type="password"
              className="form-control"
              id="exampleInputPassword2"
              placeholder="Password"
              value={userPassword}
              onChange={(e) => setUserPassword(e.target.value)}
            />
          </div> */}
            {signupIsPending ? (
              <>
                <button
                  type="submit"
                  className="btn-auth-sj btn btn-primary"
                  disabled
                >
                  Save Details
                </button>
              </>
            ) : (
              <>
                <button type="submit" className="btn-auth-sj btn btn-primary">
                  Save Details
                </button>
              </>
            )}
          </form>
        </div>
      </div>
    </>
  );
};

export default SaveUserDetails;

The part where error is Comming

.catch((error) => {
        console.log(error + "In update profile");
      });

Due to this my displayName Is not getting saved and after submitting user is getting logged out automatically. I also asked this question previously and implemented it as answered Is their any function signupwithphonenumber in firebase just like signupwithemailandpassword? (for web) I want to make user register with his creds Thanks In advance

Dharmaraj
  • 47,845
  • 8
  • 52
  • 84
  • Which function here throws the error? Can you also share what the `signUp()` function is from `usePhoneSignUp` ? – Dharmaraj Jun 25 '22 at 13:43
  • @Dharmaraj In updateUserProfile the Catch block is throwing error.And in SignUp() function we are just storing more user data by creating a collection named users which get stored in firestoredatabase( by more user data I mean user-type which is related to my project). – Arjav Sethi Jun 25 '22 at 15:25
  • @Dharmaraj you can just ignore the signup function its has nothing to do with error. – Arjav Sethi Jun 25 '22 at 15:27
  • Ok here's the twist the session was getting expired because we were spam testing . – Arjav Sethi Jun 25 '22 at 15:43
  • After waiting for some time it got automatically resolved idk how . – Arjav Sethi Jun 25 '22 at 15:44
  • Oh okay, you have two Solutions to avoid this spam testing. One, use test phone numbers from Firebase console. Two, use Firebase emulator. I prefer Firebase emulator because it creates a six digit code for you in the logs and you can emulate all services. Post the answer to your question to help others in future because your code is working. – Obum Jun 25 '22 at 17:47
  • turns out i was wrong before related to session, there is still the same issue and it is arising when I am updating user displayName in firebase auth . This time the error is occurring from the beginning . @Dharmaraj – Arjav Sethi Jun 26 '22 at 11:12
  • Can you try `auth.currentUser.reload().then(() => { /* update profile function here */ })` in the `updateUserProfile` function? – Dharmaraj Jun 26 '22 at 11:15
  • @Dharmaraj It's working fine now no error ,let me test some more time – Arjav Sethi Jun 26 '22 at 11:27

1 Answers1

1

Okay So the problem got resolved gust by wrapping updateProfile function(one provided by firebase) into

auth.currentUser.reload().then(() => { /* update profile function here */ })

Or In my case :-

 const updateUserProfile = () => {
    auth.currentUser.reload().then(() => {
      updateProfile(auth.currentUser, {
        displayName: name,
      })
        .then(() => {
          console.log("profile Updated" + name + " " + email);
        })
        .catch((error) => {
          console.log(error + "In update profile");
        });
      updateEmailUser();
    });
  };