Home > Blockchain >  Object Destructuring with React hook
Object Destructuring with React hook

Time:03-12

There is a simple code:

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

export default function App() {
  const { register, formState: { errors }, handleSubmit } = useForm();
  
  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input {...register("firstName", { required: true })} />
      {errors.firstName?.type === 'required' && "First name is required"}
      
      <input {...register("lastName", { required: true })} />
      {errors.lastName && "Last name is required"}
      
      <input type="submit" />
    </form>
  );
}

form the official React Hook Form page.

My question regards the code:

const { register, formState: { errors }, handleSubmit } = useForm();

from the example above. I understand that it's just the Object Destructuring on hook function assignment but how the formState: { errors } works there and what does it really does?

CodePudding user response:

Nested destructuring:

function nested() {
    return {
        really: { nested: { object: 42 } },
    };
}

const { really: { nested: { object } } } = nested();

console.log(object); // 42

Note that you cannot use really or nested as identifiers, only object, because that's what's being extracted.

CodePudding user response:

Suppose your userForm() function is defined as

function useForm() {
    return {
        formState: {
            errors: {}
        }
    }
}

Then you may do something like

let { formState: { errors}} = useForm();

This is equallent to

let useFromResponse = userForm();
let errors = useFormResponse.formState.errors;

You are doing a nested destructing here and yaa once done you can use errors but not formState.

  • Related