Home > OS >  react-hook-form when editing doesn't update
react-hook-form when editing doesn't update

Time:11-01

I can't find a way to provide the existing information from the DB to the react-hook-form library to revalidate when clicking submits and to update it if the data was changed.

The problem is when clicking on submit button, this object will shown without any value for firstName and lastname:

{firstName: undefined, lastname: undefined}

Simplified version of my component:

import React from "react";
import { useForm } from "react-hook-form";
import { TextField } from "@material-ui/core";

const App = (props) => {
  const { register, handleSubmit} = useForm();

  const onSubmit = (data) => {
    console.log(data);   // ---> here
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <h2>Step 1</h2>
      <label>
        First Name:
        <TextField {...register("firstName")} defaultValue="firstname" />
      </label>
      <label>
        Last Name:
        <TextField {...register("lastname")} defaultValue="lastname" />
      </label>
      <input type="submit" />
    </form>
  );
};

export default App

Any idea how to create a form that allows you to edit the fields?

Check out on codesandbox

CodePudding user response:

The problem is with the TextFiled component. the register is not set correctly.

According to the MUI documentation:

props:inputProps type:object description:Attributes applied to the input element.

So you need to pass the register throw the inputProps:

<TextField inputProps={register("firstName")} defaultValue="firstname" />

<TextField inputProps={register("lastname")} defaultValue="lastname" />
  • Related