Open petrbela opened 4 years ago
I'm not sure about your use case but you can try giving an empty string.
I also faced the same issue, instead it changes the value attribute of the html input element by it doesn't update the UI
Are there any solutions or work arounds for this issue?
@ShaunKT this is expected behavior. Setting an input's value to undefined sets the input's value={undefined}
which in React means it is an uncontrolled input and React will not perform an update on it. Formik is a Controlled Input library unlike something like react-hook-form which uses uncontrolled inputs. A controlled input's empty value should be an empty string, because that is what the user interacts with.
@ShaunKT A simple workaround is to call setFieldValue('name', '')
followed by setFieldValue('name', undefined)
. It's not ideal as it causes two rerenders but it should get the job done.
You can also create your own version of Field which does something like:
const TextInput = (fieldProps) => {
const [field] = useField(fieldProps);
return <input {...field} value={field.value ?? ''} />
}
Or in v3 you can do:
const formatString = (value) => value ?? '';
const MyForm = () => (
<Formik {...props}>
<Field name="myField" format={formatString} />
</Formik>
)
@ShaunKT A simple workaround is to call
setFieldValue('name', '')
followed bysetFieldValue('name', undefined)
. It's not ideal as it causes two rerenders but it should get the job done.
Use NaN
worked for my number fields too, setFieldValue('age', NaN)
Yup didn't like using NaN
for number fields, and I feel like that isn't the same as undefined
or null
. We should be able to clear a field with undefined.
🐛 Bug report
Current Behavior
When calling
setFieldValue('name', undefined)
, Formik correctly deletes the value from the state but doesn't update the Field value.Expected behavior
Should clear the text input value.
Reproducible example
https://codesandbox.io/s/formik-setformvalue-to-undefined-doesnt-clear-input-dgqtu
Suggested solution(s)
🤷♂️
Additional context
N/A
Your environment