Home > front end >  POST request in react hook form not fetching the user input
POST request in react hook form not fetching the user input

Time:11-02

I am working on an address book and I have fetched all the data from this API url:

enter image description here

enter image description here

Would this one be a good way to approach the POST request?

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

    fetch(URL, {
      method: 'POST',
      body: JSON.stringify({
        id:'',
        name: '',
        email: '',
        address1:'',
        address2:'',
        city:'',
        phone:''    
      }),
        headers: {
          'Content-type': 'application/json; charset=UTF-8'
        },
    })
      .then((response) => response.json())
      .then((json) => console.log(json)); 
  }
  
    return (
      <>
        <Header>New user</Header>
          <FormContainer>
            <Form onSubmit={handleSubmit(onSubmit)}>      
              <input type="text" placeholder="name"  {...register("name", { required: true })} />
              {errors.name && <span>This field is required</span>}

              <input type="text" placeholder="email" {...register("email", { required: true })} />
              {errors.email && <span>This field is required</span>}

              <input type="text" placeholder="address1"{...register("address1", { required: true })} />
              {errors.address1 && <span>This field is required</span>}

              <input type="text" placeholder="address2"{...register("address2", { required: true })} />
              {errors.address2 && <span>This field is required</span>}

              <input type="text" placeholder="city"{...register("city", { required: true })} />
              {errors.city && <span>This field is required</span>}
              
              <input type="text" placeholder="phone"{...register("phone", { required: true })} />
              {errors.phone && <span>This field is required</span>}
              
              <input type="submit" />
            </Form>
          </FormContainer>
      </>  
    );
}

CodePudding user response:

Okay, after checking the react-hook-form docs, here is a possible solution:

In the docs, it says that your onSubmit will have a data param:

  const onSubmit = (data) => alert(JSON.stringify(data));

Which means that you can use that in your onSubmit too. Try changing your onSubmit to use the data parameter:

  const onSubmit = (data) => {
    fetch(URL, {
      method: 'POST',
      body: JSON.stringify(data),

And revert the change I suggested earlier regarding handleSubmit. This is correct:

    <Form onSubmit={handleSubmit(onSubmit)}>      
  • Related