PluginProbe
ElasticPress / 4.3.0
ElasticPress v4.3.0
5.3.5 5.3.4 3.6.5 3.6.6 4.0.0 4.0.1 4.1.0 4.2.0 4.2.1 4.2.2 4.3.0 4.3.1 4.4.0 4.4.1 4.5.0 4.5.1 4.5.2 4.6.0 4.6.1 4.7.0 4.7.1 4.7.2 5.0.0 5.0.1 5.0.2 All 108 releases
elasticpress / assets / js / instant-results / hooks.js

hooks.js in ElasticPress 4.3.0, at assets/js/instant-results/hooks.js

71 lines 1.6 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
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