how to use inertia-react with useForm

Table of contents

No heading

No headings in the article.

The problem I'm having is: after resetting the form with useForm's reset(), the data still doesn't change!

import {  useForm } from "@inertiajs/inertia-react";

const defaultFilterData: Filters = {
    search: '',
    trashed: '',
    role: ''
  }

const {data, get,setData, reset} = useForm(defaultFilterData)

In the above code, use setData in the form to update the value of the corresponding field, and then want to reset the form to the initial state, use reset, in

const handleReset = e => {
    e.preventDefault();
    // reset() is not here, in button onClick function
    query();
  };
<form onSubmit={handleSubmit} onReset={handleReset}>
 ......
 </form>

It appears that the form value has not been changed, and it is effective to click the reset button twice. At first I thought it was the option preserveState: true in the get method: it was caused by removing the preserveState, but the data of the form value was all gone after the submit button was clicked.

 const query = pickBy(data);
    get(Routes.users(Object.keys(query).length ? query : { remember: "forget" }), {
      preserveState: true,
      preserveScroll: true,
      replace: true,
      only: ["users"],
    });
  };

So I continued to investigate, thinking about what went wrong. After trying, I found that putting reset() on the onClick of the reset button solved it:

 <Button type="submit" colorScheme="facebook" width="full" disabled={processing}>
              inquire
 </Button>
  <Button type="reset" colorScheme="gray" width="full" onClick={() => { reset() }}>
              reset
  </Button>

Why is this? It is a problem of the rendering time process of the function component render of react, and the problem of using hooks!