Why Using HTML Tag Caused Redux State to Reset

Imagine a form inside a React-Redux application. Every time the user fills one of the fields in the form, Redux state is changed. Submit button sends HTTP POST request to the server and redirects to the next screen. Unfortunately, occasionally the submit button causes the application to go back to the login page, instead.

This is the situation I’ve encountered while transforming a Sails MVC app into React-Redux. Since it didn’t happen constantly, I figured it’s a race condition, and while debugging using Redux DevTools I noticed that @@INIT action appears instead of the list of my predefined form actions.

A quick solution would be of course not to use this tag, or choose one of the available form libraries. While I was able to handle the cons of these solutions, such as needing to implement the validations in case of just removing the tag, or needing to embed a new external library in the project had I chosen to use an existing library, I wanted to dig deep and understand why it happens.

This is what I’ve found:

In one of React official documentation > Main concepts > Forms’ examples, the onSubmit function is connected to the

tag, this way:

and inside it the default behavior is prevented:

handleSubmit(e) {
e.preventDefault();
}

It worked. But what is the default behavior that is prevented, why does it cause the state to reset, and why only sometimes?

The answer was unexpectedly in the network tab of the DevTools. When clicking on the submit didn’t result with the expected behavior, the HTTP POST request was cancelled (appears in the network tab in red), and instead a GET request was sent with the form data in the URL.

This is how

works from before the days of Ajax. On submit, an http call is invoked, by default — it’s GET. When this happened before the Axios HTTP call, it caused the cancellation of the Axios call, and the server responded in a way that caused the app to reset. When the Axios call happened first — the app worked as expected.

One of the main things that I’ve learned from this bug is that knowledge from ages ago can be useful in todays development.

read original article here