Created
May 10, 2022 09:00
-
-
Save pc035860/fb166558bef80ae82578267fa65161ea to your computer and use it in GitHub Desktop.
useDebounceInput demonstration
This file contains hidden or 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 React from 'react'; | |
import PropTypes from 'prop-types'; | |
import { InputGroup as BPInputGroup } from '@blueprintjs/core'; | |
import useDebounceInput from './useDebounceInput'; | |
const InputGroup = ({ value, onChange, debounceWait, ...restProps }) => { | |
const debounce = useDebounceInput({ | |
value, | |
onChange, | |
wait: debounceWait, | |
}); | |
return ( | |
<BPInputGroup | |
{...restProps} | |
value={debounce.value} | |
onChange={debounce.onChange} | |
/> | |
); | |
}; | |
InputGroup.propTypes = { | |
value: PropTypes.string, | |
onChange: PropTypes.func, | |
debounceWait: PropTypes.number, | |
}; | |
InputGroup.defaultProps = { | |
debounceWait: 0, | |
}; | |
export default InputGroup; |
This file contains hidden or 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 React from 'react'; | |
import { useField } from 'formik'; | |
import InputGroup from './InputGroup' | |
const MyTextField = ({ label, ...props }) => { | |
const [field, meta, helpers] = useField(props); | |
return ( | |
<> | |
<label> | |
{label} | |
<InputGroup {...field} {...props} debounceWait={300} /> | |
</label> | |
{meta.touched && meta.error ? ( | |
<div className="error">{meta.error}</div> | |
) : null} | |
</> | |
); | |
}; | |
export default MyTextfield; |
This file contains hidden or 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 { useState, useCallback, useEffect } from 'react'; | |
import debounce from 'lodash.debounce'; | |
export default ({ value, onChange, wait }) => { | |
const [localValue, setLocalValue] = useState(''); | |
const triggerOnChange = useCallback( | |
debounce(evt => { | |
onChange(evt); | |
}, wait), | |
[wait, onChange] | |
); | |
const handleChange = useCallback( | |
evt => { | |
const val = evt.target.value; | |
setLocalValue(val); | |
if (wait) { | |
evt.persist(); | |
triggerOnChange(evt); | |
} | |
else { | |
onChange(evt); | |
} | |
}, | |
[setLocalValue, wait, onChange, triggerOnChange] | |
); | |
useEffect( | |
() => { | |
setLocalValue(value); | |
}, | |
[value] | |
); | |
return { | |
value: localValue, | |
onChange: handleChange, | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment