A simple way to update state after a form submits in React
posted 2022.01.17 by Clark Wilkins, Simplexable

While working on some form logic in React Hook Forms, I ran into difficulty trying to use reset(), and also to re-render the page after the form submits. This turns out to be two things which, for someone without a great deal of React experience, seem to be very hard to locate on the Web. So here is my solution from research and experimentation.

The first part is how to render the form again. Essentially, what needs to happen is updating state, but how this is done is not so clear. What I had setup is something like this (heavily simplified)

const [thisStateValue, setThisStateValue]
.
.
.
useEffect( () => {

fetchData();

// eslint-disable-next-line react-hooks/exhaustive-deps
}, [] );

async function fetchData() {

// get a data value from the database...
setThisStateValue( resultFromDatabase)

}

The first part is pretty simple — setting up Hooks to declare and access a state value: thisStateValue.

The section useEffect is setting up values from calls to database tables and storing them in state.

The actual database calls are made in a function fetchData which is external to useEffect, so it is accessible to other functions. (See "Rules of Hooks".)

Now, to get the re-render, we need to call fetchData(); after the doSubmit method executes successfully. Assuming that the scope of data returned by fetchData includes the data you just submitted, you get a state change, and therefore, a re-render.

The second part is resetting the form. As I said in the beginning, I was not able to get reset() to work, but I did employ a method from this Stack Overflow post that did the trick: e.target.reset();.

Here's my (excerpted) doSubmit function

const onSubmit = async ( data, e ) => { // adds a new comment

try {

const { value1, value2, ... valueN } = data;

// store these values in the database

fetchData(); // forces the page update because state is changed
e.target.reset(); // resets the form on the screen
reset(); // resets the form data internal to React Hook Forms
} catch( err ) {}

}

It's amazing how something so fundamental in terms of global use-cases is so hard to discern from the web. Most articles I read stopped at console.log(data), and said nothing about form resets or how to get the page to re-render without a reload. I hope this helps others.

Addendum: I have not tested this yet, but it seems that if you set defaultValue on form inputs here, the reset() will restore them as well.