0

The problem is: the message only show in second call of handleSubmit. what should I do ? The use case for this hook is: when validateLogin return a message, a toast is dispatched in screen, see below in loginForm component.

the code:

export default function useLoginForm() {
  const [message, setMessage] = useState("");
  const [payload, setPayload] = useState<PayloadLogin>({
    email: "foo",
    password: "bar",
  });
  const { validateLogin, isLoading } = useAuth()

  async function handleSubmit(e: FormEvent) {
    e.preventDefault();

    const axiosResponse = await validateLogin(payload);
    setMessage( axiosResponse.message);
  }
  return { message, handleSubmit, isLoading }
}
export default function LoginForm() {
  const [showMessage, setShowMessage] = useState(false)
  const {message, handleSubmit, isLoading }= useLoginForm();

  function handleClose(){
    setShowMessage(false);
  };

  function handleOpen(){
    if(message && !isLoading) setShowMessage(true)
  }

  useEffect(()=>{
    handleOpen()
  },[ message, isLoading ])
   return (

      <ToastComponent isVisible={showMessage} onClose={handleClose}>
         {message}
      </ToastComponent>
      <form onSubmit={handleSubmit}>
         //form
      </form>
)

Validate function:

export function useAuth() {
  const [isLoading, setIsLoading] = useState(false);
  const [message, setMessage] = useState("");

  async function validateLogin(payload) {
    setIsLoading(true);

    try {
      await axios.post("user/login", JSON.stringify(payload));
    } catch (handledError) {
      const messageError = (handledError.response?.data.error ||
        "server problems...")

      setMessage(messageError)
    } finally {
      setIsLoading(false);
    }
    return { message };
  }
  return{ validateLogin, isLoading}
}

  • Try not to [shadow variables](https://stackoverflow.com/a/53734745/283366) like `message`, `success` and `statusCode`. It makes code confusing – Phil Jun 06 '22 at 23:56
  • `useState` is async, so after `setMessage` you cannot see `message` immediately. If you want to handle logic for `axiosResponse.data.message`, you should use it directly instead of `message` under the same function `handleSubmit` – Nick Vu Jun 07 '22 at 01:24

1 Answers1

1

Avoid returning message. You're using setMessage(messageError) to set useState's value. There's no need to return message. Also in the jsx try to use ternary operator to avoid error's.

  { message ? 
    <ToastComponent isVisible={showMessage} onClose={handleClose}>
     {message}
    </ToastComponent> : "" }
  <form onSubmit={handleSubmit}>
     //form
  </form>