I'm trying to add debounce functionality to my React app, and want to do it without a library like loadash, 3rd party node module, etc. I tried with some posts there, but nothing worked for me.
Basically, in handleSearch I just dispatch redux action which performs a query to API endpoint and in input bind value to pice of redux state and call handleSearch onChange.
My code is:
const handleSearch = (e: React.FormEvent<HTMLInputElement>) => {
const value = e.currentTarget.value
dispatch(setSearch(value))
}
And later in return
<input type="text" value={searchQuery} onChange={handleSearch} />
Also, my action:
export const searchMovies = (category: String, searchQuery: string) => async (dispatch: Dispatch<ControlDispatchTypes>) => {
try {
dispatch({
type: SEARCH_LIST_LOADING
})
let res: any;
if (searchQuery.length >= 3) {
res = await axios.get(`https://api.themoviedb.org/3/search/${category}?api_key=xxxxxxxxxx&query=${searchQuery}`)
}
dispatch({
type: SEARCH_LIST_SUCCESS,
payload: res.data.results
})
} catch (error) {
dispatch({
type: SEARCH_LIST_FAIL
})
}
}
and a piece of the reducer used for the search:
...
case SET_SEARCH:
return {
...state,
search: action.payload
}
case SEARCH_LIST_LOADING:
return {
...state,
searchLoading: false
}
case SEARCH_LIST_SUCCESS:
return {
...state,
searchLoading: false,
items: action.payload
}
case SEARCH_LIST_FAIL:
return {
...state,
searchLoading: false
}
...