2023-01-20 12:16:18 +01:00
|
|
|
import {useEffect, useState} from "react";
|
|
|
|
|
|
|
|
|
|
|
|
export default function useAsyncSearch(callback, minLength = 1) {
|
|
|
|
|
|
|
|
const [searchString, setSearchString] = useState("");
|
|
|
|
const [results, setResults] = useState(null);
|
2024-03-27 16:27:26 +01:00
|
|
|
const [isSearching, setSearching] = useState(false);
|
2023-01-20 12:16:18 +01:00
|
|
|
|
|
|
|
useEffect(() => {
|
2023-01-25 14:15:34 +01:00
|
|
|
if (minLength > 0 && (!searchString || searchString.length < minLength)) {
|
2023-01-20 12:16:18 +01:00
|
|
|
setResults([]);
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2024-03-27 16:27:26 +01:00
|
|
|
if (!isSearching) {
|
|
|
|
setSearching(true);
|
|
|
|
callback(searchString).then(results => {
|
|
|
|
setResults(results || null);
|
|
|
|
setSearching(false);
|
|
|
|
});
|
|
|
|
}
|
2023-01-20 12:16:18 +01:00
|
|
|
}, [searchString]);
|
|
|
|
|
|
|
|
return [searchString, setSearchString, results];
|
|
|
|
}
|