简体   繁体   中英

How to listen for changes on formik field with nested values?

What I want to do is when certain field from formik change, do something.

eg

useEffect(() => {
    // do something
}, [values.someField])

But if I have a dynamic name value ( from props ), that can be anything (eg field.name , field[0].otherField , level1.level2.level3 ) how can I make this effect?

const MyComponent = ({ name }) => {
    const { values } = useFormikContext()

    useEffect(() => {
        // do something
    }, [/* what to put here? */]) 

    // ...
}

I figure it out, I need to use getIn from formik

import { useFormikContext, getIn } from `formik`

const MyComponent = ({ name }) => {
    const { values } = useFormikContext()

    const fieldValue = getIn(values, name)

    useEffect(() => {
        // do something when some field in the form changes
    }, [fieldValue]) 

    // ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM