Search code examples
reactjsrequestfetch-api

POST request in react hook form not fetching the user input


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

https://jsonplaceholder.typicode.com/users

The API cannot really be modified, but it should behave "like if" according to this message in the documentation: "resource will not be really updated on the server but it will be faked as if."

I have set up the react hook form but when I submit my form this is what I get in the dev tools tab network? Shouldn't be showing the user inputs at this point instead of empty string for all fields? The id is the only thing that gets updated. Is there anything wrong with my Submit function or the actual fetch? Is it ok I have the POST fetch in this component where I have my form as well or should be in the same component where I have the GET request?

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>
      </>  
    );
}

Solution

  • 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)}>