| 1 |
import { useCallback, useRef } from '@wordpress/element'; |
| 2 |
import { apiEndpoint, apiHost } from './config'; |
| 3 |
|
| 4 |
/** |
| 5 |
* Get debounced version of a function that only runs a given ammount of time |
| 6 |
* after the last time it was run. |
| 7 |
* |
| 8 |
* @param {Function} callback Function to debounce. |
| 9 |
* @param {number} delay Milliseconds to delay. |
| 10 |
* @returns {Function} Debounced function. |
| 11 |
*/ |
| 12 |
export const useDebounce = (callback, delay) => { |
| 13 |
const timeout = useRef(null); |
| 14 |
|
| 15 |
return useCallback( |
| 16 |
(...args) => { |
| 17 |
window.clearTimeout(timeout.current); |
| 18 |
|
| 19 |
timeout.current = window.setTimeout(() => { |
| 20 |
callback(...args); |
| 21 |
}, delay); |
| 22 |
}, |
| 23 |
[callback, delay], |
| 24 |
); |
| 25 |
}; |
| 26 |
|
| 27 |
/** |
| 28 |
* Get a callback function for retrieving search results. |
| 29 |
* |
| 30 |
* @returns {Function} Memoized callback function for retrieving search results. |
| 31 |
*/ |
| 32 |
export const useGetResults = () => { |
| 33 |
const abort = useRef(new AbortController()); |
| 34 |
const request = useRef(null); |
| 35 |
|
| 36 |
/** |
| 37 |
* Get new search results from the API. |
| 38 |
* |
| 39 |
* @param {URLSearchParams} urlParams Query arguments. |
| 40 |
* @returns {Promise} Request promise. |
| 41 |
*/ |
| 42 |
const getResults = async (urlParams) => { |
| 43 |
const url = `${apiHost}${apiEndpoint}?${urlParams.toString()}`; |
| 44 |
|
| 45 |
abort.current.abort(); |
| 46 |
abort.current = new AbortController(); |
| 47 |
|
| 48 |
request.current = fetch(url, { |
| 49 |
signal: abort.current.signal, |
| 50 |
headers: { |
| 51 |
Accept: 'application/json', |
| 52 |
}, |
| 53 |
}) |
| 54 |
.then((response) => { |
| 55 |
return response.json(); |
| 56 |
}) |
| 57 |
.catch((error) => { |
| 58 |
if (error?.name !== 'AbortError' && !request.current) { |
| 59 |
throw error; |
| 60 |
} |
| 61 |
}) |
| 62 |
.finally(() => { |
| 63 |
request.current = null; |
| 64 |
}); |
| 65 |
|
| 66 |
return request.current; |
| 67 |
}; |
| 68 |
|
| 69 |
return useCallback(getResults, []); |
| 70 |
}; |
| 71 |
|