Mide
Mide

Reputation: 21

React hook error is returning an empty object

I want to display the error message on the paragraph element, but the error (message) returns an empty object. Here's the code

import React, { useState } from "react";
import { useForm } from "react-hook-form";

export default function FormInputs() {
  const {
    register,
    handleSubmit,
    formState: { errors },
  } = useForm();
<form onSubmit={handleSubmit(onSubmit)}>
        <div className="mb-5 mt-5">
          <label
            htmlFor="exampleFormControlTextarea1"
            className="form-label mb-3"
          >
            Name
          </label>
          <input
            type="text"
            name="name"
            className="form-control form-control-lg"
            id="exampleFormControlTextarea1"
            placeholder="Mide Olabanji"
          />
        </div>
        <div className="mb-5">
          <label htmlFor="exampleFormControlInput1" className="form-label mb-3">
            Email address <span className="required"> *</span>
          </label>
          <input
            type="email"
            name="email"
            className="form-control form-control-lg"
            id="exampleFormControlInput1"
            placeholder="[email protected]"
            {...register("email", { required: "Please include your email" })}
          />
        </div>
        <h6>{error.email.message}</h6>
<footer>
          <a href="/next">
            <input
              type="submit"
              className="btn btn-lg mt-5 ms-2 next-btn"
              value="Next"
            />
          </a>
          </footer>

The object is only updated on submit so i tried to use state to update it:

const [error, setError] = useState("");

function onSubmit(data) {
    console.log(data);
    setError(errors.email.message);
  }
...
<h6>{error}</h6>

but it still doesn't work.

Upvotes: 2

Views: 2340

Answers (1)

Mnai
Mnai

Reputation: 507

  1. Make sure you're accessing the errors object and not error (you might be doing it correctly but your code is broken up into 2 snippets so its a bit confusing)

  2. Remove the name="email" from your input as {...register()} returns a name. I assume this is where you error is at.

properties type, classname, placeholder are all okay to have but the register function returns onChange, onBlur, ref and name so there is no need to override it as I assume it will cause errors

          <input
            type="email"
            className="form-control form-control-lg"
            id="exampleFormControlInput1"
            placeholder="[email protected]"
            {...register("email", { required: "Please include your email" })}
          />

Upvotes: 1

Related Questions