mirror of
https://github.com/getredash/redash.git
synced 2025-12-19 17:37:19 -05:00
* Dialog wrapper: stop using promises to handle results - replace with callbacks * Dialog wrapper: handle async operation on close
34 lines
982 B
JavaScript
34 lines
982 B
JavaScript
import { useState, useEffect, useRef } from "react";
|
|
import { useDebouncedCallback } from "use-debounce";
|
|
|
|
export default function useSearchResults(fetch, { initialResults = null, debounceTimeout = 200 } = {}) {
|
|
const [result, setResult] = useState(initialResults);
|
|
const [isLoading, setIsLoading] = useState(false);
|
|
const currentSearchTerm = useRef(null);
|
|
const isDestroyed = useRef(false);
|
|
|
|
const [doSearch] = useDebouncedCallback(searchTerm => {
|
|
setIsLoading(true);
|
|
currentSearchTerm.current = searchTerm;
|
|
fetch(searchTerm)
|
|
.catch(() => initialResults)
|
|
.then(data => {
|
|
if (searchTerm === currentSearchTerm.current && !isDestroyed.current) {
|
|
setResult(data);
|
|
setIsLoading(false);
|
|
}
|
|
});
|
|
}, debounceTimeout);
|
|
|
|
useEffect(
|
|
() =>
|
|
// ignore all requests after component destruction
|
|
() => {
|
|
isDestroyed.current = true;
|
|
},
|
|
[]
|
|
);
|
|
|
|
return [doSearch, result, isLoading];
|
|
}
|