Home > Back-end >  react-hook-form: how to add default values to the input field
react-hook-form: how to add default values to the input field

Time:08-29

In my project using a react-hook-form to create and update values. but the problem is whenever click on the update button shows an empty form without the data. The lines

import { useState } from "react"
import { useCountryCreate } from "../api/usecountrycreate"
import { useForm } from "react-hook-form"


export const CountryCreateUpdateForm = ({ defaultValues, onFormSubmit, isLoading }) => {

    const { register, handleSubmit } = useForm({ defaultValues });
  
    const onSubmit = handleSubmit((data) => {
      onFormSubmit(data)
    })

  return (

        <form onSubmit={onSubmit}>
            <div>
              <label for="name">Name</label>
              <input {...register('name')} type="text" name="name" />   
            </div>         
            <button type="submit" >submit</button>
        </form>



  )
}

When console this "defaultValues.data.name " then it shows the exact name value which I want to edit but is not displayed in the field.

enter image description here

Please give me suggestions, that will help me to overcome this problem.

CodePudding user response:

It seems likely here that your {defaultValues} object is probably not properly configured. it should have a property called name. If it doesn't, hook-form can't properly match it to your input registered as 'name' :)

CodePudding user response:

Seems like defaultValues object is not proper.

In your case I assume it's like this:

defaultValues =  {
  data: {
      name: '',
      category: '',
      ...
    }
}

It should be like this:

 defaultValues = {
      name: '',
      category: '',
      ...
    }

So change defaultValues object to the mentioned above or use the below code to set defaultValues in useForm

const { register, handleSubmit } = useForm({ defaultValues: defaultValues?.data });
  • Related