jaredpalmer / formik

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

Setting setFieldValue to undefined doesn't clear text input #2180

Open petrbela opened 4 years ago

petrbela commented 4 years ago

🐛 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

Software Version(s)
Formik 2.1.1
React 16.12.0
TypeScript N/A
Browser Chrome
npm/Yarn N/A
Operating System Mac
mrmuhammadali commented 4 years ago

I'm not sure about your use case but you can try giving an empty string.

Mahandrisoa commented 4 years ago

I also faced the same issue, instead it changes the value attribute of the html input element by it doesn't update the UI

ShaunKT commented 3 years ago

Are there any solutions or work arounds for this issue?

johnrom commented 3 years ago

@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.

petrbela commented 3 years ago

@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.

johnrom commented 3 years ago

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>
)
thanhnha121 commented 1 year ago

@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.

Use NaN worked for my number fields too, setFieldValue('age', NaN)

CarolynWebster commented 7 months ago

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.