Skip to content

Instantly share code, notes, and snippets.

@pc035860
Created May 10, 2022 09:00
Show Gist options
  • Save pc035860/fb166558bef80ae82578267fa65161ea to your computer and use it in GitHub Desktop.
Save pc035860/fb166558bef80ae82578267fa65161ea to your computer and use it in GitHub Desktop.
useDebounceInput demonstration
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;
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;
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