Last active
August 9, 2019 00:18
-
-
Save elsangedy/093633344ca6878a458aafb2a0ba0d6e to your computer and use it in GitHub Desktop.
FormikFieldSpy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useMemo, useEffect } from 'react' | |
import { getIn, connect } from 'formik' | |
import { useThrottle } from './useThrottle' | |
export const FormikFieldSpy = connect( | |
({ field, onChange, timeout, formik }) => { | |
const value = useMemo(() => getIn(formik.values, field), [ | |
field, | |
formik.values | |
]) | |
const handle = useThrottle(onChange, timeout) | |
useEffect(() => { | |
handle(value, formik) | |
}, [value, onChange]) | |
return null | |
} | |
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useRef, useEffect, useCallback } from 'react' | |
export function useThrottle(fun, timeout) { | |
const timer = useRef(null) | |
const cancel = useCallback(() => { | |
if (timer.current) { | |
clearTimeout(timer.current) | |
timer.current = null | |
} | |
}, [timer]) | |
useEffect(() => { | |
cancel() | |
}, [cancel]) | |
return (...args) => { | |
cancel() | |
timer.current = setTimeout(() => { | |
timer.current = null | |
fun.apply(this, args) | |
}, timeout) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment