jaredpalmer / formik

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

Setting errors with a deeply nested object in an array results in a type error when accessing the errors object #3857

Closed kylemcd closed 1 year ago

kylemcd commented 1 year ago

Bug report

Current Behavior

When accessing the errors from the Formik component children props, and there is a nested object within an array of values, the errors object results in an error once you descend into the array, props?.foo?.[0]?.bar?.id It errors at bar with this error:

Property 'foo' does not exist on type 'FormikProps<Type>'

Expected behavior

Typescript is able to follow the type passed into FormikHelpers so that it can be used for the errors object without a type error.

Reproducible example

https://codesandbox.io/s/formik-codesandbox-template-forked-lsyntr?file=/index.tsx

Suggested solution(s)

I assume the FormikErrors type that maps over the values would need to be adjusted in order to get this to work. Would be willing to play around with that once I free up from other obligations.

Your environment

Software Version(s)
Formik 2.4.3
React 8.2.0
TypeScript 5.16
Browser Chrome
npm 9.8.1
Operating System Mac OS
vennilamahalingam commented 1 year ago

When you need to access errors of the props object then it should be props?errors?.foo?.[0]?.bar?.idand not props?.foo?.[0]?.bar?.id

Refer - https://codesandbox.io/s/formik-codesandbox-template-forked-zt872v?file=/index.tsx

Is this what you intend to do ?

kylemcd commented 1 year ago

I borked the code sandbox it seems and I haven't found a good way to isolate a reproduction. I think this has to do with the complexity of the state object I'm trying to use within the form.

I did find a solution though, using the getIn utility from Formik.

Instead of accessing the error in the Field you're trying to display like:

errors?.name

You can instead do this:

getIn(errors, 'name')

This works for deeply nested values as well:

getIn(errors, `foo[index].bar.baz')

So if someone runs across this issue in the future where typescript just isn't playing nicely with the error object Formik produces, this is a great workaround!