Skip to content

Instantly share code, notes, and snippets.

@elsangedy
Last active August 9, 2019 00:18
Show Gist options
  • Save elsangedy/093633344ca6878a458aafb2a0ba0d6e to your computer and use it in GitHub Desktop.
Save elsangedy/093633344ca6878a458aafb2a0ba0d6e to your computer and use it in GitHub Desktop.
FormikFieldSpy
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
}
)
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