jaredpalmer / formik

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

Pass formik helpers inside the validate function #2998

Closed allroundexperts closed 3 years ago

allroundexperts commented 3 years ago

Feature request

Current Behavior

The callback function for the validate prop of the Formik component receives form values only.

Desired Behavior

Apart from the form values, helpers such as setFieldValue passed onto the callback function would make things a lot easier.

Suggested Solution

In the Formik component, just pass on the helpers while calling the validate prop.

Who does this impact? Who is this for?

This is for people who want to pass on the setFieldValue as context to the yup schema. Some interdependent fields in the schema are async and require communication with an external api. If the schema test function returns true for one of the field, the value of the api call is often the value of the second interdependent field. This will save us from doing multiple api calls.

Describe alternatives you've considered

The alternative that I'm using right now is that in the yup schema, I'm doing just the synchronous validation (ie no calls to the api). In the Field component, I'm using a useEffect hook with the value, error and isValidating properties from the useFormikState hook. If value is true, error is none and isValidating is false, then I make an api call to the external service and based on the results of that api call, I either call setFieldValue or setFieldError. Here's a sample of what I am doing right now.

  const { errors, touched, values, isValidating, setFieldValue, setFieldError } = useFormikContext();

  React.useEffect(() => {
    (async () => {
      if(!isValidating && !errors["myfield"] && values["myfield"]){
        const rawData = await fetch(`${apiEndpoint}`);
        const res = await rawData.json();
        if(!res.error){
            setFieldValue("myotherfield", value)
        }else{
          setFieldError("myfield", "Custom error");
        }
      }
    })();
  }, [values["myfield"], errors["myfield"], isValidating]);
github-actions[bot] commented 3 years ago

This issue is stale because it has been open 30 days with no activity. Remove stale label or comment or this will be closed in 60 days