Write data from database to inputs handled with react-hook-form

Viewed 314

I have a big form like this with multiple inputs like this (not showing all because is not necessary). I am handling the data with react hook form library.

  const {register, reset} = useForm();

  return (
         <input
           {...register("name")}
           type="text"
           value={product.name}
           placeholder="Nombre Producto"
         />
         <input
           {...register("regular_price")}
           type="number"
           defaultValue={product.regular_price}
           placeholder="precio regular"
         />
   )

You can see there is a default value depending on a product, that is a state which I set when data comes from the database.

My form is filled with the data of the product I want to edit when I click on one. The problem is it only fills the inputs once. After I make a reset() all the inputs go blank and they don't fill again.

What is the best approach to make inputs "fill" with the values from my database without an onChange?

I hope you can help me. Thanks in advance!

1 Answers

The solution was to use the reset when I clicked on a product and set the values from the api to the values of my form like this:

    useFormProps.reset({
      available_colors: producto.available_colors,
      available_sizes: producto.available_sizes,
      categories: producto.categories,
      description: producto.description,
      featuredImage: producto.featuredImage,
      freeShipping: producto.freeShipping,
      images: producto.images,
      is_published: producto.is_published,
      name: producto.name,
      price: producto.price,
      regular_price: producto.regular_price,
      sale_price: producto.sale_price,
      short_description: producto.short_description,
      sku: producto.sku,
      status: producto.status,
      stock_quantity: producto.stock_quantity,
    })

Related