1
+ import { ComponentRef , useMemo , useRef } from 'react' ;
2
+ import { useRouter } from 'next/router' ;
3
+ import { useSuggestedQuestionsQuery , useCreateThreadMutation , useThreadLazyQuery } from '@/apollo/client/graphql/home.generated' ;
4
+ import { useGetSettingsQuery } from '@/apollo/client/graphql/settings.generated' ;
5
+ import { CreateThreadInput } from '@/apollo/client/graphql/__types__' ;
6
+ import useHomeSidebar from '@/hooks/useHomeSidebar' ;
7
+ import useAskPrompt from '@/hooks/useAskPrompt' ;
8
+ import { Path } from '@/utils/enum' ;
9
+
10
+ export const useHome = ( ) => {
11
+ const $prompt = useRef < ComponentRef < typeof Prompt > > ( null ) ;
12
+ const router = useRouter ( ) ;
13
+ const homeSidebar = useHomeSidebar ( ) ;
14
+ const askPrompt = useAskPrompt ( ) ;
15
+
16
+ const { data : suggestedQuestionsData } = useSuggestedQuestionsQuery ( {
17
+ fetchPolicy : 'cache-and-network' ,
18
+ } ) ;
19
+ const [ createThread , { loading : threadCreating } ] = useCreateThreadMutation ( {
20
+ onError : ( error ) => console . error ( error ) ,
21
+ onCompleted : ( ) => homeSidebar . refetch ( ) ,
22
+ } ) ;
23
+ const [ preloadThread ] = useThreadLazyQuery ( {
24
+ fetchPolicy : 'cache-and-network' ,
25
+ } ) ;
26
+
27
+ const { data : settingsResult } = useGetSettingsQuery ( ) ;
28
+ const settings = settingsResult ?. settings ;
29
+ const isSampleDataset = useMemo (
30
+ ( ) => Boolean ( settings ?. dataSource ?. sampleDataset ) ,
31
+ [ settings ] ,
32
+ ) ;
33
+
34
+ const sampleQuestions = useMemo (
35
+ ( ) => suggestedQuestionsData ?. suggestedQuestions . questions || [ ] ,
36
+ [ suggestedQuestionsData ] ,
37
+ ) ;
38
+
39
+ const onSelectQuestion = async ( { question } ) => {
40
+ $prompt . current . submit ( question ) ;
41
+ } ;
42
+
43
+ const onCreateResponse = async ( payload : CreateThreadInput ) => {
44
+ try {
45
+ askPrompt . onStopPolling ( ) ;
46
+ const response = await createThread ( { variables : { data : payload } } ) ;
47
+ const threadId = response . data . createThread . id ;
48
+ await preloadThread ( { variables : { threadId } } ) ;
49
+ router . push ( Path . Home + `/${ threadId } ` ) ;
50
+ } catch ( error ) {
51
+ console . error ( error ) ;
52
+ }
53
+ } ;
54
+
55
+ return {
56
+ $prompt,
57
+ homeSidebar,
58
+ askPrompt,
59
+ isSampleDataset,
60
+ sampleQuestions,
61
+ onSelectQuestion,
62
+ onCreateResponse,
63
+ threadCreating,
64
+ } ;
65
+ } ;
0 commit comments