Wreeecks
Wreeecks

Reputation: 2274

How to use setFieldValue in <Formik>?

I don't fully understand the difference between <Formik/> and useFormik() implementation. I hope someone can point me to the right direction.

Is it possible to use formik.setFieldValue() with <Formik />? I need to set the value in the async callback.

If so, can you please share a snippet on how to do this. TIA

Upvotes: 1

Views: 9506

Answers (2)

Yosef Tukachinsky
Yosef Tukachinsky

Reputation: 5895

In any children component of formik, you can use the hook useFormikContext, which return all data you got in render props on a formik. so:

const {setFieldValue} = useFormikContext();

also, you can use hook to get stuuf for specific field, using useField:

const [fieldInput, fieldMeta, fieldHelpers] = useField('fieldName');
fieldHelpers.setValue(value);

Note that you must to be in inner component. not same component where you define the Formik component, but one of its childs

Upvotes: 2

Muhammad Bilal Bangash
Muhammad Bilal Bangash

Reputation: 1236

enter image description here here is the screenshot of that piece of code

Upvotes: 2

Related Questions