I have a search form which is changing my params on my page. It's actually working fine, however whenever you input any character at all, it will automatically refresh the page and re-fetch results. This is not what I want.
Is there a better way to action this, e.g debounce the search results for an idle time on the user input OR dynamically fetch?
See my code below:
function handleParamChange(e) {
const param = e.target.name //name may be desc
const value = e.target.value
setParams(prevParams => {
return { ...prevParams, [param]: value}
})
}
<SearchForm params={params} onParamChange={handleParamChange}/>
This will then be fed to component as such.
const SearchForm = ({params, onParamChange}) => {
return (
<GeneralFilterContainer>
<TextField id="standard-basic"
label="Search Roles"
variant="standard"
size="small"
onChange={onParamChange}
value={params.what}
name="what"
type="text"
/>
</GeneralFilterContainer>
)
}
export default SearchForm
As above, i just want to debounce and dynamically fetch rather then it just reload every time.
Regards
The onChange event gets fired after each key the user types, so yes, your app in this case will reload after each keypress. A simple solution woulb be to add this function in your component:
function debounce(func, wait, immediate) {
var timeout;
return function executedFunction() {
var context = this;
var args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
which i got from here. After that, change your onChange event to this:
onChange={debounce(onParamChange, 250)}
I hope this works, i can't test it right now.