Search code examples
reactjsreact-hook-formreact-query

react query is refreshing hook form after successful submission using useMutation


I am trying to add some data in a json-server file. For that I am using a hook form, and for posting the data I am using useMutation. I am able to add in json-server file, but the problem is, after successful insertion, the page is reloading automatically. I want to navigate to another page after success, but not able to do so. Can you guide me to do that and stop the refreshing? The code is:

CreateUser.jsx page

import CommonForm from "../components/commonform";
import { useMutation } from "react-query";

const addUser = async (data) => {
  let res = await axios.post("http://localhost:1000/user", data);
  return res;
};

const CreateUser = () => {

  const { mutate } = useMutation(addUser);  

  const submitHandler = (data) => {
    console.log("Data submitted from the form", data);
    mutate(data);
  };
 
  return (
    <div>
      <CommonForm view="createForm" submitHandler={submitHandler} />
    </div>
  );
};

export default CreateUser;

CommonForm.jsx

import { useForm } from "react-hook-form";

const CommonForm = ({ view, submitHandler }) => {

  const { register, handleSubmit, formState } = useForm();
  const { errors } = formState;

   return (
    <div>
      <form onSubmit={handleSubmit(submitHandler)} noValidate>
        {/* username field with validation */}
        <label htmlFor="uname">User Name: </label>
        <input
          type="text"
          id="uname"
          {...register("username", {
            required: {
              value: true,
              message: "* User name is required",
            },
            minLength: {
              value: 3,
              message: "Minimum length 3",
            },
          })}
          autoComplete="off"
        />

        {/* username validation message */}
        <br />
        <p>{errors.username?.message}</p>
        <br />

        {/*  email field with validation */}
        <label htmlFor="email">Email : </label>
        <input
          type="email"
          id="email"
          {...register("email", {
            required: {
              value: true,
              message: "* email is required",
            }
          })}
          autoComplete="off"
        />

        {/* error validation message */}
        <br />
        <p>{errors.email?.message}</p>
        <br />

        <input type="submit" value="Submit" />
      </form>
    </div>
  );
};

export default CommonForm;

The db.json file:

{
  "user": [
    {
      "id": "1",
      "username": "John Doe",
      "email": "[email protected]"
    },
    {
      "id": "22f8",
      "username": "hello",
      "email": "[email protected]"
    }
  ]
}

The last data of "Hello" is added by the form.


Solution

  • I used useNavigate from React Router to navigate to a different page after a successful mutation and ensured that the form submission logic prevented the page reload by correctly handling it with react-hook-form's handleSubmit.

    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.3.1/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.3.1/umd/react-dom.production.min.js"></script>
    
    
    import { useMutation } from "react-query";
    import { useNavigate } from "react-router-dom"; // Import useNavigate
    import CommonForm from "../components/commonform";
    import axios from "axios";
    
    // Mutation function to add user
    const addUser = async (data) => {
      let res = await axios.post("http://localhost:1000/user", data);
      return res;
    };
    
    const CreateUser = () => {
      const navigate = useNavigate(); // Initialize useNavigate
      const { mutate } = useMutation(addUser, {
        onSuccess: () => {
          // Redirect to another page on success, e.g., "/users"
          navigate("/users");  // Use the route where you want to navigate
        },
        onError: (error) => {
          // Handle any errors if needed
          console.error("Error adding user:", error);
        }
      });
    
      const submitHandler = (data) => {
        console.log("Data submitted from the form", data);
        mutate(data); // Trigger mutation with form data
      };
    
      return (
        <div>
          <CommonForm view="createForm" submitHandler={submitHandler} />
        </div>
      );
    };
    
    export default CreateUser;
    
    
    
    import { useForm } from "react-hook-form";
    
    const CommonForm = ({ view, submitHandler }) => {
      const { register, handleSubmit, formState } = useForm();
      const { errors } = formState;
    
      return (
        <div>
          <form onSubmit={handleSubmit(submitHandler)} noValidate>
            {/* username field with validation */}
            <label htmlFor="uname">User Name: </label>
            <input
              type="text"
              id="uname"
              {...register("username", {
                required: {
                  value: true,
                  message: "* User name is required",
                },
                minLength: {
                  value: 3,
                  message: "Minimum length 3",
                },
              })}
              autoComplete="off"
            />
            {/* username validation message */}
            <br />
            <p>{errors.username?.message}</p>
            <br />
    
            {/* email field with validation */}
            <label htmlFor="email">Email : </label>
            <input
              type="email"
              id="email"
              {...register("email", {
                required: {
                  value: true,
                  message: "* Email is required",
                },
              })}
              autoComplete="off"
            />
            {/* email validation message */}
            <br />
            <p>{errors.email?.message}</p>
            <br />
    
            <input type="submit" value="Submit" />
          </form>
        </div>
      );
    };
    
    export default CommonForm;