Home > Mobile >  Not getting updated error value from custom useAuth hook in React
Not getting updated error value from custom useAuth hook in React

Time:01-12

I wrote a custom useAuth hook that returns functions like signup, login and an error. But If there is an error such as wrong email and password, it doesn't return an updated error state variable in the Login.js and redirects the user to the /dashboard on form submit even if there is an error.

Login.js

import { useEffect, useState } from "react";
import useAuth from "../hooks/useAuth";
import { useNavigate } from "react-router-dom";

const Login = () => {
  const [user, setUser] = useState({});
  const { login, error } = useAuth();
  const navigate = useNavigate();

  const handleChange = (e) => {
    setUser({ ...user, [e.target.name]: e.target.value });
  };
  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      await login(user);
      navigate("/dashboard");
    } catch (error) {
      console.log(error);
    }
  };

  return (
    <div>
      <h1>Log In</h1>
      <form onSubmit={handleSubmit}>
        <div>
          <label htmlFor="email">Email</label>
          <input onChange={handleChange} type="email" name="email" id="email" />
        </div>
        <div>
          <label htmlFor="password">Password</label>
          <input
            onChange={handleChange}
            type="password"
            name="password"
            id="password"
          />
        </div>
        <button>Log In</button>
      </form>
    </div>
  );
};

export default Login;

useAuth.js

import { useEffect, useState } from "react";
import { account } from "../appwrite/config";
import { ID } from "appwrite";

const useAuth = () => {
  const [error, setError] = useState(null);

  const signup = async (user) => {
    try {
      await account.create(
        ID.unique(),
        user.email,
        user.password,
        user.username
      );
    } catch (error) {
      console.log(error);
      setError(error.message);
    }
  };

  const login = async (user) => {
    setError(null);
    try {
      await account.createEmailSession(user.email, user.password);
    } catch (error) {
      console.log(error);
      setError(error.message);
    }
  };

  const logout = async () => {
    try {
      await account.deleteSession("current");
    } catch (error) {
      console.log(error);
      setError(error.message);
    }
  };
  return { signup, login, logout, error };
};

export default useAuth;

CodePudding user response:

In of the useAuth functions, you need to throw the error inside the catch block so that the error is caught in Login.js. For example, try changing your login function to this:

const login = async (user) => {
  setError(null);
  try {
    await account.createEmailSession(user.email, user.password);
  } catch (error) {
    console.log(error);
    setError(error.message);
    throw error; // Error that will be caught in Login.js
  }
};
  • Related