jaredpalmer / formik

Build forms in React, without the tears 😭
https://formik.org
Apache License 2.0
33.88k stars 2.79k forks source link

Stale validation errors shown #2534

Open krvajal opened 4 years ago

krvajal commented 4 years ago

🐛 Bug report

Current Behavior

I have a form with a complex validation logic that runs on the server. Sometimes I am seeing stale validation errors being shown on the form. This seems to happen in the following case 1) Form data is changed (and invalid) 2) Request to validate is sent to the server (not resolved yet) (REQUEST 1) 3) Form data is changed again (now with valid data) 3) Request to validate is sent to the server (not resolved yet) (REQUEST 2) 4) REQUEST 2 resolves and no validation error is shown 5) REQUEST 1 resolves and validation errors from prev invalid state is shown

Expected behavior

Reproducible example

The example below reproduces the error if you type in the input, then clear it and type again.

import React from "react";
import { useFormik } from "formik";

let count = 0;
function validate({ a, b }) {
  return new Promise(resolve => {
    setTimeout(
      () =>
        resolve({
          a: !a && "err_a"
        }),
      ++count % 2 === 0 ? 1000 : 250
    );
  });
}

export default function App() {
  const { values, errors, handleChange, handleSubmit } = useFormik({
    initialValues: {
      a: ""
    },
    validate: validate,
    onSubmit() {}
  });

  return (
    <div className="App">
      <form onSubmit={handleSubmit}>
        <div style={{ marginBottom: 20 }}>
          <input name="a" value={values.a} onChange={handleChange} />
          <div style={{ color: "red" }}> {errors.a}</div>
        </div>
      </form>
    </div>
  );
}

Suggested solution(s)

The dispatch call here https://github.com/jaredpalmer/formik/blob/master/packages/formik/src/Formik.tsx#L333 should be aborted if the form values changes.

Additional context

Your environment

Software Version(s)
Formik 2.1.4
React 16.12.0
TypeScript -
Browser -
npm/Yarn -
Operating System -
ekabolotina commented 1 year ago

The issue is still there.