前端: 添加useSearch搜索钩子
This commit is contained in:
parent
a31caafcf6
commit
89ee45a7eb
34
frontend/src/renderer/hooks/useSearch.js
Normal file
34
frontend/src/renderer/hooks/useSearch.js
Normal file
@ -0,0 +1,34 @@
|
|||||||
|
import { useState, useCallback } from 'react';
|
||||||
|
import api from '../utils/api';
|
||||||
|
|
||||||
|
export const useSearch = () => {
|
||||||
|
const [results, setResults] = useState([]);
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
const [keyword, setKeyword] = useState('');
|
||||||
|
|
||||||
|
const search = useCallback(async (q, type) => {
|
||||||
|
if (!q || q.length < 2) {
|
||||||
|
setResults([]);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setLoading(true);
|
||||||
|
try {
|
||||||
|
const url = `/api/search?q=${encodeURIComponent(q)}${type ? `&type=${type}` : ''}`;
|
||||||
|
const data = await api.get(url);
|
||||||
|
setResults(data.files || []);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Search failed:', error);
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const clear = useCallback(() => {
|
||||||
|
setResults([]);
|
||||||
|
setKeyword('');
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return { results, loading, keyword, setKeyword, search, clear };
|
||||||
|
};
|
||||||
|
|
||||||
|
export default useSearch;
|
||||||
Loading…
Reference in New Issue
Block a user