mirror of
https://github.com/actualbudget/actual.git
synced 2026-03-11 12:43:09 -05:00
60 lines
1.5 KiB
TypeScript
60 lines
1.5 KiB
TypeScript
import { useState, useMemo, useEffect, useRef } from 'react';
|
|
|
|
import { debounce } from 'lodash';
|
|
|
|
import type { Query } from 'loot-core/shared/query';
|
|
|
|
import * as queries from '@desktop-client/queries';
|
|
|
|
type UseTransactionsSearchProps = {
|
|
updateQuery: (updateFn: (searchQuery: Query) => Query) => void;
|
|
resetQuery: () => void;
|
|
dateFormat: string;
|
|
delayMs?: number;
|
|
};
|
|
type UseTransactionsSearchResult = {
|
|
isSearching: boolean;
|
|
search: (searchText: string) => void;
|
|
};
|
|
|
|
export function useTransactionsSearch({
|
|
updateQuery,
|
|
resetQuery,
|
|
dateFormat,
|
|
delayMs = 150,
|
|
}: UseTransactionsSearchProps): UseTransactionsSearchResult {
|
|
const [isSearching, setIsSearching] = useState(false);
|
|
|
|
const updateQueryRef = useRef(updateQuery);
|
|
updateQueryRef.current = updateQuery;
|
|
|
|
const resetQueryRef = useRef(resetQuery);
|
|
resetQueryRef.current = resetQuery;
|
|
|
|
const updateSearchQuery = useMemo(
|
|
() =>
|
|
debounce((searchText: string) => {
|
|
if (searchText === '') {
|
|
resetQueryRef.current?.();
|
|
setIsSearching(false);
|
|
} else if (searchText) {
|
|
resetQueryRef.current?.();
|
|
updateQueryRef.current(previousQuery =>
|
|
queries.transactionsSearch(previousQuery, searchText, dateFormat),
|
|
);
|
|
setIsSearching(true);
|
|
}
|
|
}, delayMs),
|
|
[dateFormat, delayMs],
|
|
);
|
|
|
|
useEffect(() => {
|
|
return () => updateSearchQuery.cancel();
|
|
}, [updateSearchQuery]);
|
|
|
|
return {
|
|
isSearching,
|
|
search: updateSearchQuery,
|
|
};
|
|
}
|