Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(deps): update dependency formik to v2 #3143

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

renovate[bot]
Copy link
Contributor

@renovate renovate bot commented Sep 10, 2024

This PR contains the following updates:

Package Change Age Adoption Passing Confidence
formik (source) ^1.5.1 -> ^2.0.0 age adoption passing confidence

Release Notes

jaredpalmer/formik (formik)

v2.4.6

Compare Source

v2.4.5

Compare Source

Patch Changes

v2.4.4

Compare Source

Patch Changes

v2.4.3

Compare Source

Patch Changes

v2.4.2

Compare Source

Patch Changes

v2.4.1

Compare Source

Patch Changes
  • 2b194c2 #​3808 Thanks @​NagaiKoki! - fix type of setFieldValue function

  • 708bcb2 #​3813 Thanks @​probablyup! - Revert FieldArray "shouldComponentUpdate" performance optimization. As it turns out, it's a common use case to have JSX controlled via non-Formik state/props inside of FieldArray, so it's not safe to cancel re-renders here.

  • 187e47d #​3815 Thanks @​probablyup! - Revert Yup transform support for the time being, this may be re-introduced in a future release under an opt-in prop.

v2.4.0

Compare Source

Minor Changes

v2.3.3

Compare Source

Patch Changes
  • f075a0c #​3798 Thanks @​probablyup! - Fixed the use of generics for the ArrayHelpers type such that any[] is the default array type and for each individual method the array item type can be overridden if necessary.

v2.3.2

Compare Source

Patch Changes
  • f086b5a #​3237 Thanks @​pieplu! - Changed getIn to return undefined when it can't find a value AND a parent of that value is "falsy" ( "" / 0 / null / false )

  • 6d8f018 #​3792 Thanks @​probablyup! - Update the type for setFieldValue to reflect the returned Promise and potential returned error(s).

v2.3.0

Compare Source

Minor Changes
  • 73de78d #​3788 Thanks @​probablyup! - Added typescript generics to ArrayHelpers interface and its methods so that users who use TypeScript can set the type for their arrays and have type safety on array utils. I have also gone ahead and made supplying a type for the generic optional for the sake of backwards compatibility so any existing TS code that does not give a type for the FieldArray will continue to work as they always have.

  • 39a7bf7 #​3786 Thanks @​probablyup! - Yup by default only allows for cross-field validation within the
    same field object. This is not that useful in most scenarios because
    a sufficiently-complex form will have several yup.object() in the
    schema.

    const deepNestedSchema = Yup.object({
      object: Yup.object({
        nestedField: Yup.number().required(),
      }),
      object2: Yup.object({
        // this doesn't work because `object.nestedField` is outside of `object2`
        nestedFieldWithRef: Yup.number()
          .min(0)
          .max(Yup.ref('object.nestedField')),
      }),
    });

    However, Yup offers something called context which can operate across
    the entire schema when using a \$ prefix:

    const deepNestedSchema = Yup.object({
      object: Yup.object({
        nestedField: Yup.number().required(),
      }),
      object2: Yup.object({
        // this works because of the "context" feature, enabled by $ prefix
        nestedFieldWithRef: Yup.number()
          .min(0)
          .max(Yup.ref('$object.nestedField')),
      }),
    });

    With this change, you may now validate against any field in the entire schema,
    regardless of position when using the \$ prefix.

v2.2.10

Compare Source

Patch Changes
  • 22e236e #​3784 Thanks @​probablyup! - Improve performance of the FieldArray component by adding a shouldComponentUpdate check; this should help avoid unnecessary re-renders which may affect the performance of a form.

  • bc9cb28 #​3785 Thanks @​probablyup! - Fixed field error state for array fields that have an error and become empty through an API like arrayHelpers.remove.

    The prior behavior resolved the field error to [undefined], now it is simply undefined.

  • 9cbf150 #​3787 Thanks @​probablyup! - Fix infinite loop issue in Field when field helpers (setTouched, etc) are used as an argument in React.useEffect.

  • 9c75a9f #​3780 Thanks @​probablyup! - Fixed an issue with array field errors being incorrectly split into an array of individual characters instead of an array of error strings.

  • 35fa4cc #​3783 Thanks @​probablyup! - Fix validation of deep.dot.path field references when using the validateField API.

v2.2.9

Compare Source

Patch Changes

v2.2.8

Compare Source

Patch Changes

v2.2.7

Compare Source

Patch Changes
  • e50040a #​2881 Thanks @​jinmayamashita! - Prevent calling getSelectedValues when the element has not options

  • 31405ab #​3201 Thanks @​artola! - Fixes regression that resulted in error update race condition from when using validateOnMount

  • c2d6926 #​2995 Thanks @​johnrom! - Allow explicitly setting <form action> to empty string (#​2981). Note: previous code which passed an empty string would result in a noop (simply appending # to the url), but this will now result in a form submission to the current page.

v2.2.6

Compare Source

Patch Changes

v2.2.5

Compare Source

Patch Changes

v2.2.4

Compare Source

Patch Changes

v2.2.3

Compare Source

Patch Changes

v2.2.2

Compare Source

Patch Changes

v2.2.1

Compare Source

Patch Changes

v2.2.0

Compare Source

Minor Changes
  • 4148181 #​2794 Thanks @​jaredpalmer! - setValue can now optionally accept a function as a callback, exposing React.SetStateAction functionality. Previously, only the entire object was
    allowed which caused issues with stale props.

    setValues(prevValues => ({...prevValues, ... }))

v2.1.7

Compare Source

Patch Changes

v2.1.6

Compare Source

v2.1.5

Compare Source

Bugfixes

  • Properly handle nested array data in prepareDataForValidation. (#​2265)
  • Fix 2.1.4 regression with initialValues updating (#​2318)
  • Correct import of LowPriority from scheduler
  • Updated innerRef type signature (#​2325)
  • Fix handleChange / handleBlur typings (#​2472)
  • Fix peer dependency version (#​2451)
  • Fixed @typescript-eslint/unbound-method warning.

Internal

Legal

  • License changed from MIT to Apache 2.0. Formik is 100% still open source. We don't want people using the logo/trademark commercially without our permission.
  • Intellectual Property and Copyright transferred from Jared Palmer to Formik Inc. Happy to answer questions via DM at [email protected]

Commits

  • Properly handle nested array data in prepareDataForValidation. (#​2265)
  • Fix 2.1.4 regression with initialValues updating (#​2318)
  • Added "shouldValidate" to "setValue" and "setTouched" field hel… (#​2371)
  • Add FieldProps change to v2 migration guide (#​2356)
  • Correct import of LowPriority from scheduler
  • Fix: return onSubmit promise result in submission (#​2420)
  • fix: Update innerRef type signature (#​2325)
  • Fix handleChange / handleBlur typings (#​2472)
  • Fix peer dependency version (#​2451)
  • Make validateOnMount rerun validations when initialValues have changed
  • Update LICENSE
  • Merge pull request #​2507 from stefanoverna/fix-validateonmount
  • Merge pull request #​2438 from helious/master
  • Fixes @​typescript-eslint/unbound-method.

v2.1.4

Compare Source

v2.1.3

Compare Source

Patches
  • Start examples page: 8f998ae
  • Be nicer around unspecified checkboxes: #​2198. Previously, Formik would throw if a checkbox's key wasn't specified in initialValues and a value wasn't specified at /. Now we are nicer about it, and set the next value to true instead of throwing.
  • Fix compat with latest @​types/react: #​2214
  • Attempt to fix codesandbox: #​2218
  • Try using forwardRef (bypassed commit hooks, sorry!): 67ff970
  • Revert "Try using forwardRef (bypassed commit hooks, sorry!)": 4ff1c5c
  • Update useField docs: #​2233
  • Update field.md: #​2228
  • Update SECURITY.md to conform to semver: #​2227
  • Make num of rows in example equal: #​2226
  • Fix grammar and typos: #​2225
  • Load Snack code from external source so it stays up to date: #​2242
Credits

Huge thanks to @​mackness, @​JanCizmar, @​is2ei, @​leonvisscher, @​stephan281094, and @​brentvatne for helping!

v2.1.2

Compare Source

Patches
  • Fix broken formatting on useField docs: 587c5ee
  • Merge pull request #​2175 from zingerj/patch-1: 7173d74
  • Fix hasOwnProperty: #​2178
  • Fix for Object-like data without hasOwnProperty: #​2177
  • Fix now.sh upstream: 4b23009
  • Fix now docs deploys by specifying node engine: 7f00fd6
  • Add generic to FieldHelperProps typings: #​2179
  • Run tests on node 12: 9c1b0d0
  • Fix typo in Field documentation: #​2183
  • Patch to getValueForCheckbox to resolve issues with undefined values: #​2188
  • Fix use event callback in handlers: #​2187
  • Update type of as and component props in FieldConfig to enable using forwardRef wrapped components with Field and FastField (#​2193): #​2182
  • Trigger onReset when resetForm is called, not just handleReset: #​2201
  • Upgrade deps: #​2203
  • Document the v2 breaking change of validate: #​2195
  • Add submitForm to FormikHelpers to allow form re-submit: #​2185
  • Run validationSchema for validateField calls: #​1784
  • Expose formikbag as imperative methods: #​1972
Credits

Huge thanks to @​BjoernRave, @​emrosenf, @​kristenmills, @​dremex, @​zachintosh, @​deini, @​brunohkbx, @​Menardi, @​gwn, @​fabb, and @​jamesmosier for helping!

v2.1.1

Compare Source

Patches
  • Update website: d1059c8
  • Small spelling error: #​2161
  • Correctly handle single checkboxes and grouped ones values: #​2159. Fixed a bug when value was not specified on a checkbox as well as when there is just one checkbox.
  • Adds a community article: #​2157
  • Update contributing guidelines start step: #​2158
  • Force FieldArray to use latest values for validation: #​2166
Credits

Huge thanks to @​wallymathieu, @​eliamaino-fp, and @​mrmuhammadali for helping!

v2.1.0

Compare Source

Minor Changes
  • Add FieldHelpers object to the array returned by useField: #​2124. This
    exposes three helper functions to allow you to imperatively change the
    field in question:

    1. setValue(value: any)
    2. setTouched(value: boolean)
    3. setError(value: string)

    Before

    const MyInput = (props) => {
     const formik = useFormikContext() 
     const [field, meta] = useField(props)
     const handleThing = () => {
        formik.setFieldValue(props.name, 'boop') 
     }
     // ...
    }

    After

    const MyInput = (props) => {
     const [field, meta, helpers] = useField(props)
     const handleThing = () => {
        helpers.setValue('boop') 
     }
     // ...
    }
Credits

Huge thanks to @​drivasperez for helping!

v2.0.11

Compare Source

Patches
  • Keep empty array values on FieldArray: #​2144
Credits

Huge thanks to @​viniciusdacal for helping!

v2.0.10

Compare Source

TS Patch

  • Fix useField<T> generic.

v2.0.9

Compare Source

Patches
  • Hotfix: Revert throwing combined errors: #​2103
  • Abort submit if instance of real Error: #​2104
  • Remove inline cDU usage in FieldArray: #​2114
  • Remodel FieldArray validation side effect to cDU: #​2115
  • Allow forced validation to run anywhere #​2116
  • Handle promise rejection in handleSubmit #​2136
  • Fix unhandled promise exception in low priority validation #​2119

v2.0.8

Compare Source

Patches
  • Hotfix: Revert throwing combined errors: #​2103
  • Abort submit if instance of real Error: #​2104
  • Remove inline cDU usage in FieldArray: #​2114
  • Remodel FieldArray validation side effect to cDU: #​2115

v2.0.7

Compare Source

Improvements

  • Massive perf boost over 2.0.6! We now save renders by comparing errors more efficiently in useFormik/Formik.
  • FastField is now even faster. We fixed up our implementation of shouldComponentUpdate by refactoring the component away from using static contextType and back to using the connect() higher order component.

Bug fixes

  • Fixed regression where dirty is wasn't re-evaluated after resetForm()

  • Fixed regression where handleChange would explode when event.target didn't exist (e.g. event.currentTarget

  • If there are validation errors while calling submitForm(), the promise will now rejects with errors (and of course abort the submit). Previously, it would abort the submit and resolve. The nuance is hard to describe so here is the difference.

    Before (2.0.6)

     submitForm() // imagine there are some Yup validation errors
      .then(() => console.log("abort submit, did not call onSubmit, and end up here"))
      .catch(() => console.log("abort submit, did not call onSubmit, but only because of a runtime error"));

    After (2.0.7)

     submitForm() // imagine there are some Yup validation errors
      .then(() => console.log("executed onSubmit"))
      .catch((err) => console.log("aborted submit attempt"));

    2.0.6: https://codesandbox.io/s/gracious-noether-bu8u6
    2.0.7: https://codesandbox.io/s/objective-perlman-jxhuq

Commits

v2.0.6

Compare Source

Bugfix

  • Change onSubmit's type signature to accept Promise<any>. This allows folks to return a promise that returns something (which is pretty common). Sorry about that folks.

Commits

  • Generate 2.0.6 docs e933b9c
  • Correct 2.0.5 docs 67e9071
  • Change type signature of onSubmit to accept Promise 2738bbc

v2.0.5

Compare Source

Bugfixes

  • Changed onSubmit behavior to mimic v1 if the function is synchronous. This means fixes a bug where isSubmitting was never toggled. To summarize: If onSubmit is async, then Formik will automatically set isSubmitting to false on your behalf once the submission is completed. This means you do NOT need to call formikBag.setSubmitting(false) manually in v2. HOWEVER, if your onSubmit function is synchronous (e.g. v1), then you need to still call setSubmitting(false) on your own. (#​1987)
  • Fix checkbox bug with null value (#​2027)
  • Update validateFormWithLowPriority with to use fresh values (#​2025)

Commits

v2.0.4

Compare Source

Bugfixes

  • Fix prepareDataForValidation work with instances (#​1949) ec7810a. this fixed a regression where people were having issues when keeping wonky objects like Moment() as values.
  • Fixed scheduler dep.

Internal

  • Moved docs (and jaredpalmer.com) off of Netlify to Now.sh v2.
  • Bumped React and TypeScript
  • Cleaned up migration docs

Commits

v2.0.3

Compare Source

Bugfixes

  • Fixed TypeScript when using <Form> due to omitted 2nd generic to React.forwardRef. TypeScript users should use this version.

Commits

v2.0.2

Compare Source

Bugfixes

  • Fixed return TS type of of useField so that it returns a tuple

Commits

v2.0.1

Compare Source

Formik 2 Migration Guide

Breaking Changes

Minimum Requirements
  • Since Formik 2 is built on top of React Hooks, you must be on React 16.8.x or higher
  • Since Formik 2 uses the unknown type, you must be on TypeScript 3.0 or higher
resetForm

There is only one tiny breaking change in Formik 2.x. Luckily, it probably won't impact verry many people. Long story short, because we introduced initialErrors, initialTouched, initialStatus props, resetForm's signature has changed. It now accepts the next initial state of Formik (instead of just the next initial values).

v1

resetForm(nextValues);

v2

resetForm({ values: nextValues /* errors, touched, etc ... */ });

What's New?

Checkboxes and Select multiple

Similarly to Angular, Vue, or Svelte, Formik 2 "fixes" React checkboxes and multi-selects with built-in array binding and boolean behavior. This was one of the most confusing things for people in Formik 1.x.

import React from 'react';
import { Formik, Field, Form } from 'formik';
import { Debug } from './Debug';

const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));

const CheckboxExample = () => (
  <div>
    <h1>Checkboxes</h1>
    <p>
      This example demonstrates how to properly create checkboxes with Formik.
    </p>
    <Formik
      initialValues={{
        isAwesome: false,
        terms: false,
        newsletter: false,
        jobType: ['designer'],
        location: [],
      }}
      onSubmit={async values => {
        await sleep(1000);
        alert(JSON.stringify(values, null, 2));
      }}
    >
      {({ isSubmitting, getFieldProps, handleChange, handleBlur, values }) => (
        <Form>
          {/* 
            This first checkbox will result in a boolean value being stored.
          */}
          <div className="label">Basic Info</div>
          <label>
            <Field type="checkbox" name="isAwesome" />
            Are you awesome?
          </label>
          {/* 
            Multiple checkboxes with the same name attribute, but different
            value attributes will be considered a "checkbox group". Formik will automagically
            bind the checked values to a single array for your benefit. All the add and remove
            logic will be taken care of for you.
          */}
          <div className="label">
            What best describes you? (check all that apply)
          </div>
          <label>
            <Field type="checkbox" name="jobType" value="designer" />
            Designer
          </label>
          <label>
            <Field type="checkbox" name="jobType" value="developer" />
            Developer
          </label>
          <label>
            <Field type="checkbox" name="jobType" value="product" />
            Product Manager
          </label>
          {/*
           You do not _need_ to use <Field>/useField to get this behaviorr, 
           using handleChange, handleBlur, and values works as well. 
          */}
          <label>
            <input
              type="checkbox"
              name="jobType"
              value="founder"
              checked={values.jobType.includes('founder')}
              onChange={handleChange}
              onBlur={handleBlur}
            />
            CEO / Founder
          </label>

          {/* 
           The <select> element will also behave the same way if 
           you pass `multiple` prop to it. 
          */}
          <label htmlFor="location">Where do you work?</label>
          <Field
            component="select"
            id="location"
            name="location"
            multiple={true}
          >
            <option value="NY">New York</option>
            <option value="SF">San Francisco</option>
            <option value="CH">Chicago</option>
            <option value="OTHER">Other</option>
          </Field>
          <label>
            <Field type="checkbox" name="terms" />I accept the terms and
            conditions.
          </label>
          {/* Here's how you can use a checkbox to show / hide another field */}
          {!!values.terms ? (
            <div>
              <label>
                <Field type="checkbox" name="newsletter" />
                Send me the newsletter <em style={{ color: 'rebeccapurple' }}>
                  (This is only shown if terms = true)
                </em>
              </label>
            </div>
          ) : null}
          <button type="submit" disabled={isSubmitting}>
            Submit
          </button>
          <Debug />
        </Form>
      )}
    </Formik>
  </div>
);

export default CheckboxExample;
useField()

Just what you think, it's like <Field>, but with a hook. See docs for usage.

useFormikContext()

A hook that is equivalent to connect().

<Field as>

<Field/> now accepts a prop called as which will inject onChange, onBlur, value etc. directly through to the component or string. This is useful for folks using Emotion or Styled components as they no longer need to clean up component's render props in a wrapped function.

Misc
  • FormikContext is now exported
  • validateOnMount?: boolean = false
  • initialErrors, initialTouched, initialStatus have been added
// <input className="form-input" placeHolder="Jane"  />
<Field name="firstName" className="form-input" placeholder="Jane" />

// <textarea className="form-textarea"/></textarea>
<Field name="message" as="textarea"  className="form-input"/>

// <select className="my-select"/>
<Field name="colors" as="select" className="my-select">
  <option value="red">Red</option>
  <option value="green">Green</option>
  <option value="blue">Blue</option>
</Field>

// with styled-components/emotion
const MyStyledInput = styled.input`
  padding: .5em;
  border: 1px solid #eee;
  /* ... */
`
const MyStyledTextarea = MyStyledInput.withComponent('textarea');

// <input className="czx_123" placeHolder="google.com"  />
<Field name="website" as={MyStyledInput} placeHolder="google.com"/>

// <textarea  placeHolder="Post a message..." rows={5}></textarea>
<Field name="message" as={MyStyledTextArea} placeHolder="Post a message.." rows={4}/>
getFieldProps(nameOrProps)

There are two useful additions to FormikProps, getFieldProps and getFieldMeta. These are Kent C. Dodds-esque prop getters that can be useful if you love prop drilling, are not using the context-based API's, or if you are building a custom useField.

export interface FieldInputProps<Value> {
  /** Value of the field */
  value: Value;
  /** Name of the field */
  name: string;
  /** Multiple select? */
  multiple?: boolean;
  /** Is the field checked? */
  checked?: boolean;
  /** Change event handler */
  onChange: FormikHandlers['handleChange'];
  /** Blur event handler */
  onBlur: FormikHandlers['handleBlur'];
}
getFieldMeta(name)

Given a name it will return an object:

export interface FieldMetaProps<Value> {
  /** Value of the field */
  value: Value;
  /** Error message of the field */
  error?: string;
  /** Has the field been visited? */
  touched: boolean;
  /** Initial value of the field */
  initialValue?: Value;
  /** Initial touched state of the field */
  initialTouched: boolean;
  /** Initial error message of the field */
  initialError?: string;
}

Configuration

📅 Schedule: Branch creation - "every weekend" in timezone US/Eastern, Automerge - At any time (no schedule defined).

🚦 Automerge: Disabled by config. Please merge this manually once you are satisfied.

Rebasing: Whenever PR is behind base branch, or you tick the rebase/retry checkbox.

🔕 Ignore: Close this PR and you won't be reminded about this update again.


  • If you want to rebase/retry this PR, check this box

This PR was generated by Mend Renovate. View the repository job log.

@Anas12091101 Anas12091101 self-assigned this Sep 24, 2024
@marslanabdulrauf
Copy link
Contributor

We were using refs in B2BPurchaseForm(Formik)
Formik v2.x now does not support ref now, we need to update this component by either following a new approach or create a custom Formik => jaredpalmer/formik#1603

Formik's Official Discussion around this => jaredpalmer/formik#2208

@renovate renovate bot force-pushed the renovate/formik-2.x branch 9 times, most recently from e81998d to 745627f Compare November 16, 2024 16:06
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants