Home > database >  Setting up a loading while user is still being signed in not working
Setting up a loading while user is still being signed in not working

Time:03-18

It does sign in the user but while it is loading, I wanted to put a display message that it is still loading. This is what I did and it is not working.

const [isLoading, setIsLoading] = useState(false);    
const handleSubmit = async (e) => {
        e.preventDefault();
        const auth = getAuth();
        console.log(email, password, "1");
        signInWithEmailAndPassword(auth, email, password)
          .then((userCredential) => {
            // Signed in
    
            const user = userCredential.user;
            setIsLoading(true);
           console.log("signed in")
            // ...
          })
          .catch((error) => {
            alert(error);
          });
      };

A button for the loading and submission:

 {isLoading ? (
              <>
                {" "}
          
                  <Button disabled>
                    Loading..
                  </ButtonForm>
              </>
            ) : (
              <>
                  <Buttontype="submit">Submit</Button>
              </>
            )}

CodePudding user response:

If you code, you are setting loading to true when the user is signed in. This is the opposite of what you are trying to accomplish. What you want is that the user gets immediate feedback on the button press by seeing a loading response and removing that when the user authentication is over.

It's also better practice to create a modal in case of error and to disable buttons during ongoing API calls.

export default App = () => {
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState(false);

  const handleSubmit = async (e) => {
    e.preventDefault();

    // Immediate feedback
    setIsLoading(true);

    const auth = getAuth();
    signInWithEmailAndPassword(auth, email, password)
      .then((userCredential) => {
        // Signed in
        setIsLoading(false);
      })
      .catch((error) => {
        // Not signed in
        setIsLoading(false);
        setError(true);
      });
  };

  return (
    <div>
      <button type="button" onClick={handleSubmit} disable={isLoading}>
        Click
      </button>
      {isLoading && <div>Loading ...</div>}
      {error && <div>An error has occured!</div>}
    </div>
  );
};
  • Related