forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseSearchConversations.ts
More file actions
102 lines (89 loc) · 2.59 KB
/
Copy pathuseSearchConversations.ts
File metadata and controls
102 lines (89 loc) · 2.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
'use client';
import { useState, useCallback, useRef } from 'react';
import { searchConversations as searchConversationsApi } from '@/lib/api';
import type { Conversation } from '@/types/conversation';
interface UseSearchConversationsReturn {
results: Conversation[];
loading: boolean;
error: string | null;
currentPage: number;
totalPages: number;
search: (query: string) => Promise<void>;
loadMore: () => Promise<void>;
clear: () => void;
}
export function useSearchConversations(): UseSearchConversationsReturn {
const [results, setResults] = useState<Conversation[]>([]);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [currentPage, setCurrentPage] = useState(1);
const [totalPages, setTotalPages] = useState(0);
const currentQueryRef = useRef<string>('');
const search = useCallback(async (query: string) => {
// Don't search if query is empty
if (!query.trim()) {
setResults([]);
setCurrentPage(1);
setTotalPages(0);
currentQueryRef.current = '';
return;
}
currentQueryRef.current = query;
setLoading(true);
setError(null);
try {
const response = await searchConversationsApi({
query,
page: 1,
perPage: 20,
});
setResults(response.items);
setCurrentPage(response.current_page);
setTotalPages(response.total_pages);
} catch (err) {
setError(err instanceof Error ? err.message : 'Search failed');
console.error('Search error:', err);
} finally {
setLoading(false);
}
}, []);
const loadMore = useCallback(async () => {
if (loading || currentPage >= totalPages || !currentQueryRef.current) {
return;
}
setLoading(true);
setError(null);
try {
const response = await searchConversationsApi({
query: currentQueryRef.current,
page: currentPage + 1,
perPage: 20,
});
setResults((prev) => [...prev, ...response.items]);
setCurrentPage(response.current_page);
setTotalPages(response.total_pages);
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to load more results');
console.error('Load more error:', err);
} finally {
setLoading(false);
}
}, [loading, currentPage, totalPages]);
const clear = useCallback(() => {
setResults([]);
setCurrentPage(1);
setTotalPages(0);
setError(null);
currentQueryRef.current = '';
}, []);
return {
results,
loading,
error,
currentPage,
totalPages,
search,
loadMore,
clear,
};
}