Formik: Provide a way to setFieldValue when using useField

Created on 3 Jul 2019  ·  3Comments  ·  Source: formium/formik

🚀 Feature request

I can't find any way to set the field value directly when I am using useField. The only way is onChange() which doesn't work in my use case.

Here's the use case - my component allows the user to enter a Date object. It has two text fields to set the date and time parts. When the user has fully entered both parts, I can parse the two text strings and create a Date object. However, until then I need to keep the two strings in the component's internal state.

When the user is done entering (either onBlur or pressing Enter), I can compute the Date, but I don't have any way to generate a onChange() event to set the value of the field. It would be convenient to have a method to set the field's value directly.

Here's the relevant code:

const DateTimeField = ({name, label}) => {
    const [field, meta] = useField(name);
    const [parts, setParts] = useState(computeParts(field.value));

    const handleDateTimeChanged = () => {
        const date = computeDate(parts.datePart, parts.timePart);
        field.onChange(??????);
    };

    return (
        <div>
            <TextField
                value={parts.datePart}
                onChange={event => {
                    setParts({
                        datePart: event.target.value,
                        timePart: parts.timePart
                    });
                }}
                onBlur={handleDateTimeChanged}
            />
            <TextField
                value={parts.timePart}
                onChange={event => {
                    setParts({
                        datePart: parts.datePart,
                        timePart: event.target.value
                    });
                }}
                onBlur={handleDateTimeChanged}
            />
        </div>
    );
};

Current Behavior

There is no way to set the field's value directly from useField.

Desired Behavior

There should be way to set the field's value directly from useField.

Suggested Solution

Provide a setFieldValue() method within the result of useField.

Most helpful comment

@nareshbhatia have you tried to use useFormikContext() this will provide the FormikHelpers including the setFieldValue().

All 3 comments

@nareshbhatia have you tried to use useFormikContext() this will provide the FormikHelpers including the setFieldValue().

Thanks, @atothek1, I was completely unaware of useFormikContext() (was going by this docs page). I think this will work perfectly!

Just chiming in—useFormikContext() is phenomenal and I'd love to see it mentioned in the docs. Makes a very large ordering form I have so easy to cleanly break into sections 👏

Was this page helpful?
0 / 5 - 0 ratings