foxhound87 / mobx-react-form

Reactive MobX Form State Management
https://foxhound87.github.io/mobx-react-form
MIT License
1.09k stars 129 forks source link

Adding an error to form in onSubmit clears error on first try #617

Closed j-castellanos closed 1 year ago

j-castellanos commented 1 year ago

I am experiencing an issue where if a value is entered in a field and in onSubmit you invalidate the form, the error disappears. See the following code sandbox:

https://codesandbox.io/s/intelligent-sid-jsmp85?file=/src/App.js

import React, { useMemo } from "react";
import MobxReactForm from "mobx-react-form";
import { Observer } from "mobx-react";

export default function App() {
  const form = useMemo(
    () =>
      new MobxReactForm(
        {
          fields: {
            name: {
              label: "name"
            }
          }
        },
        {
          hooks: {
            onSubmit: (_form) => {
              // simulate a quick api call
              setTimeout(() => {
                // if a value was passed in for name then this
                // does not work
                _form.invalidate("i am an error");
              }, 100);
            }
          }
        }
      ),
    []
  );

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <Observer>{() => <input {...form.$("name").bind()} />}</Observer>
      <Observer>{() => form.error && <p>{form.error}</p>}</Observer>
      <button onClick={form.onSubmit}>Submit</button>
    </div>
  );
}

If you wait long enough or hit submit again after the first time, then it works.

However the api call that I make completes quickly and I have this problem on the first try. If no value is entered for the input then the issue does not happen.

j-castellanos commented 1 year ago

Ok this seems to be related to the field blurring

foxhound87 commented 1 year ago

fixed