Should we delete field value when we delete field at the same time;
when I removed a field if it set value before, the value will be stored in values forever;
I hope field value can synchronize with field name
unregisterField = (name: string) => {
delete this.fields[name];
// here
this.values[name] && delete this.values[name];
};
i don't think this is desired. this would mean whenever a component unmounts you delete it's value.
what's the use case?
our form is generated by a file (like a JSON file), the form changed when we changed file by some cascade relations, so when we submit form, we need filter values (which changed before).
like:
[
{"name": "a", "type": "input"},
{"name": "b", "type": "input"},
{"name": "c", "type": "input"}
]
will generate:
<Field name={a} component={<input />}>
<Field name={b} component={<input />}>
<Field name={c} component={<input />}>
we change some values makes values={a:1. b: 2, c:3} and update JSON file
[
{"name": "a", "type": "input"},
{"name": "c", "type": "input"}
]
will generate:
<Field name={a} component={<input />}>
<Field name={c} component={<input />}>
when submit, the values is still values={a:1. b: 2, c:3} and i think it's not right.
If you wrap your Field in a component or write your own version of Field with connect, you can modify form state when it unmounts.
@jaredpalmer thank you for the tips
This did the tricks
const { setFieldValue } = useFormikContext()
// delete the value if the field is not mounted
useEffect(() => {
setFieldValue(FIELD_NAME, value)
return () => {
setFieldValue(FIELD_NAME, undefined)
}
}, [value])
also you can do this
useEffect(() => () => setFieldValue(FIELD_NAME, undefined), [])
maybe a better trick, this is just executed once
anyway I support the idea that this should be done by default (redux-form does it)
also you can do this
useEffect(() => () => setFieldValue(FIELD_NAME, undefined), [])maybe a better trick, this is just executed once
anyway I support the idea that this should be done by default (redux-form does it)
This works, however validations are ran on old field values resulting in errors when there shouldn't be any. As a workaround I had to add this:
useEffect(() => () => setFieldValue(FIELD_NAME, undefined, false), [FIELD_NAME, setFieldValue])
cc @yaplas
Most helpful comment
@jaredpalmer thank you for the tips
This did the tricks