File size: 2,258 Bytes
caae15f
 
 
7d9d30d
caae15f
 
 
 
 
 
 
 
 
 
 
 
7d9d30d
caae15f
 
7d9d30d
caae15f
 
7d9d30d
caae15f
 
 
 
 
7d9d30d
caae15f
 
 
 
7d9d30d
caae15f
 
 
 
d9b91ed
f730525
7d9d30d
caae15f
 
f730525
 
 
 
 
 
caae15f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"use client";

import { useState, useEffect } from "react";
import { SearchResult } from "@/app/components/ui/search/search.interface";

interface UseSearchResult {
    searchResults: SearchResult[];
    isLoading: boolean;
    handleSearch: (query: string) => Promise<void>;
}

const search_api = process.env.NEXT_PUBLIC_SEARCH_API;

const useSearch = (): UseSearchResult => {
    const [searchResults, setSearchResults] = useState<SearchResult[]>([]);
    const [isLoading, setIsLoading] = useState(false);
    const [isSearchButtonPressed, setIsSearchButtonPressed] = useState(false);

    const handleSearch = async (query: string): Promise<void> => {
        setIsSearchButtonPressed(isSearchButtonPressed);
        setIsLoading(true);

        // Check if search API is defined
        if (!search_api) {
            console.error("Search API is not defined");
            setIsLoading(false);
            return;
        }

        // Perform search logic here
        try {
            console.log("Searching for:", query);
            // check if query is empty
            if (query.trim() === "") { // Trim whitespace from query and check if it's empty
                setSearchResults([]);
                setIsLoading(false);
                return;
            }
            const response = await fetch(`${search_api}?query=${query}`, {
                signal: AbortSignal.timeout(120000), // Abort the request if it takes longer than 120 seconds
            });
            const data = await response.json();
            setSearchResults(data);
        } catch (error: any) {
            if (error.name === "AbortError") {
                console.error("Error fetching search results: Request timed out");
            } else {
                console.error("Error fetching search results:", error.message);
            }
            setSearchResults([]);
        }

        setIsLoading(false);
    };

    useEffect(() => {
        // Initial load logic if needed
        // ...

        // Cleanup logic if needed
        return () => {
            // ...
        };
    }, []); // Dependency array depends on your use case

    return {
        searchResults,
        isLoading,
        handleSearch,
    };
};

export default useSearch;