Skip to content

Instantly share code, notes, and snippets.

@michaellarrubis
Created October 19, 2022 23:32
Show Gist options
  • Save michaellarrubis/645c9a3687322d347e87c56a935a2537 to your computer and use it in GitHub Desktop.
Save michaellarrubis/645c9a3687322d347e87c56a935a2537 to your computer and use it in GitHub Desktop.
// useDebounce.js
import { useEffect } from 'react'
import useTimeout from './useTimeout'
const useDebounce = (callback, delay, dependencies) => {
const { reset, clear } = useTimeout(callback, delay)
useEffect(reset, [...dependencies, reset])
useEffect(clear, [])
}
export default useDebounce
// Implemented on Page/Component
useDebounce(() => {
if (!searchText) setCompanySuggestions(null)
if (searchText) {
const payload = {
query: searchText,
size: 5,
page: 1
}
dispatch(fetchCompanySuggestionsRequest(payload))
}
}, 300, [searchText])
const updateUrl = (queryParam, queryObject) => {
router.push(
{
pathname: `${process.env.HOST_PATH}/jobs-hiring/${queryParam ? queryParam : 'job-search'}`,
query: queryObject,
},
undefined,
{ shallow: true }
)
}
const onKeywordSearch = (val) => {
// eslint-disable-next-line
const { keyword, ...rest } = router.query
let queryObject = {}
queryObject = Object.assign({}, { ...rest, sort: val.length > 0 ? 2 : 1 })
const queryParam = conditionChecker(val, predefinedLocation, predefinedCategory)
updateUrl(queryParam, queryObject)
}
// Usage on return() with <MaterialTextFieldWithSuggestionList/>
<MaterialTextFieldWithSuggestionList
id='search'
label='Search for job title, keyword or company'
variant='outlined'
size='small'
className={styles.searchField}
defaultValue=''
searchFn={handleSuggestionSearch}
onSelect={(val) => {
onKeywordSearch(val)
}}
onKeyPress={(e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault()
onKeywordSearch((e.target as HTMLInputElement).value)
}
}}
options={suggestionList}
/>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment