mirror of
https://github.com/grafana/grafana.git
synced 2025-08-06 16:59:01 +08:00
Chore: Refactor Search out-of-order fix (#68445)
This commit is contained in:
@ -83,7 +83,7 @@ export async function getSearchResultActions(searchQuery: string): Promise<Comma
|
||||
export function useSearchResults(searchQuery: string, isShowing: boolean) {
|
||||
const [searchResults, setSearchResults] = useState<CommandPaletteAction[]>([]);
|
||||
const [isFetchingSearchResults, setIsFetchingSearchResults] = useState(false);
|
||||
const lastRequestTimestamp = useRef<number>();
|
||||
const lastSearchTimestamp = useRef<number>(0);
|
||||
|
||||
// Hit dashboards API
|
||||
useEffect(() => {
|
||||
@ -91,19 +91,20 @@ export function useSearchResults(searchQuery: string, isShowing: boolean) {
|
||||
if (isShowing && searchQuery.length > 0) {
|
||||
setIsFetchingSearchResults(true);
|
||||
debouncedSearch(searchQuery).then((resultActions) => {
|
||||
// Only update the state if this is the most recent request
|
||||
// We don't need to worry about clearing the isFetching state either
|
||||
// If there's a later request in progress, this will clear it for us
|
||||
if (!lastRequestTimestamp.current || timestamp > lastRequestTimestamp.current) {
|
||||
// Only keep the results if it's was issued after the most recently resolved search.
|
||||
// This prevents results showing out of order if first request is slower than later ones.
|
||||
// We don't need to worry about clearing the isFetching state either - if there's a later
|
||||
// request in progress, this will clear it for us
|
||||
if (timestamp > lastSearchTimestamp.current) {
|
||||
setSearchResults(resultActions);
|
||||
setIsFetchingSearchResults(false);
|
||||
lastRequestTimestamp.current = timestamp;
|
||||
lastSearchTimestamp.current = timestamp;
|
||||
}
|
||||
});
|
||||
} else {
|
||||
setSearchResults([]);
|
||||
setIsFetchingSearchResults(false);
|
||||
lastRequestTimestamp.current = timestamp;
|
||||
lastSearchTimestamp.current = timestamp;
|
||||
}
|
||||
}, [isShowing, searchQuery]);
|
||||
|
||||
|
Reference in New Issue
Block a user