how to use inertia-react with useForm

wang xiao bo 's photo
wang xiao bo
·Oct 30, 2022·

2 min read

Subscribe to my newsletter and never miss my upcoming articles

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 => {
    // reset() is not here, in button onClick function
<form onSubmit={handleSubmit} onReset={handleReset}>

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}>
  <Button type="reset" colorScheme="gray" width="full" onClick={() => { reset() }}>

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!

Share this