formik
formik copied to clipboard
setFieldTouched, setFieldValue, etc. not working with arrays in Typescript anymore
π Bug report
Current Behavior
My initial values is a property called targets which contains an array of UITargetPositions.
Calling setFieldValue or setFieldTouched results in a Typescript error that the string isn't one of the possible values.
Expected behavior
No error should be thrown.
Reproducible example
I can't get it to work with Typescript. For some reason when I changed it to .tsx it just gives me a white screen now, but here you go: https://codesandbox.io/s/formik-codesandbox-template-iru3w
Suggested solution(s)
Additional context
It seems like the only acceptable string is 'targets' so it's ignoring all of the indexes and sub properties.
Your environment
Software | Version(s) |
---|---|
Formik | 2.0.3 |
React | 16.11.0 |
TypeScript | 3.6.4 |
Browser | all |
npm/Yarn | yarn 1.19.1 |
Operating System | Win 10 Pro |
i'm facing same issue :(
it appears that setFieldValue is now attempting to be a bit too smart in terms of inferring the possible field values based on the generic form values parameter.
In the case of nested fields, this no longer works, since it doesn't attempt to traverse the possible object graph in order to derive all possible string permutations for fields - nor do I think it can or should achieve such a thing.
The issue is https://github.com/jaredpalmer/formik/blob/master/src/types.tsx#L89
setFieldValue(field: keyof Values & string, value: any, shouldValidate?: boolean): void;
keyof Values
only includes top-level properties, so cannot be used for any nested structures.
The only way I can think of to make this work (without reverting to just field: string
) would be to add a typed element further down the tree, which exposed a "scoped" version of setFieldValue
:
<Formik<Values>>
...
<FieldValueSetter<NestedValues> name="foo.bar[0].baz">
{({ setFieldValue }: FieldValueSetterProps<NestedValues>) => ...
</FieldValueSetter>
</Formik>
where FieldValueSetterProps
included
interface FieldValueSetterProps<NestedValues> {
setFieldValue(field: keyof NestedValues & string, value: any, shouldValidate?: boolean): void;
}
Hit this problem as well. The new types effectively make:
setFieldValue
setFieldError
setFieldTouched
All incompatible with nested or array values.
As a workaround, for now, I'm using as
with a string literal for one of the top level properties. Eg:
setFieldValue('category.name' as 'category', myValue)
However I don't think there is any harm in the type reverting back to string
I believe this is a duplicate of https://github.com/jaredpalmer/formik/issues/1698
Any updates on this? Stuck in here!
I totally agree this should be relaxed to be just string - it's nice to have the autocompletion for the simple case (non nested updates) but on the other hand types are just wrong currently
Is this going to be fixed soon?
Still an issue.
any fix for this π€ ?
This will be fixed?