Created
March 2, 2023 14:09
-
-
Save eddievlagea/998c54546e8a7710dd604e26f61a4b2f to your computer and use it in GitHub Desktop.
useSearch.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useQuery, QueryObserverOptions } from "@tanstack/react-query"; | |
type SearchProps = { | |
apiHostname: string; | |
apiKey: string; | |
query: string; | |
catalogId: string; | |
filterQuery?: string; | |
limit?: number; | |
offset?: number; | |
enabled?: boolean; | |
options?: QueryObserverOptions; | |
}; | |
export const searchExtraFields = | |
"document_matches,images,title,description,attributes,url"; | |
export const fetchSearchResults = async ({ | |
apiHostname, | |
apiKey, | |
query, | |
catalogId, | |
filterQuery, | |
limit = 20, | |
offset, | |
}: SearchProps) => { | |
const res = await fetch( | |
`https://${apiHostname}/v1/catalogs/${catalogId}/search?query=${encodeURIComponent( | |
query | |
)}${ | |
filterQuery ? `&filter_query=${encodeURIComponent(filterQuery)}` : "" | |
}&limit=${limit}&offset=${offset}&extra_fields=${searchExtraFields}`, | |
{ headers: { Apikey: apiKey } } | |
); | |
return res.json(); | |
}; | |
export function useSearchQuery({ | |
apiHostname, | |
apiKey, | |
query, | |
catalogId, | |
filterQuery, | |
limit = 20, | |
offset = 1, | |
enabled, | |
...options | |
}: SearchProps) { | |
const { data, error, isInitialLoading } = useQuery( | |
["search", query], | |
() => | |
fetchSearchResults({ | |
apiHostname, | |
apiKey, | |
query, | |
catalogId, | |
filterQuery, | |
limit, | |
offset, | |
}), | |
{ | |
...options, | |
enabled: enabled, | |
staleTime: Infinity, | |
} | |
); | |
return { data, error, isLoading: isInitialLoading }; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
const { data, isLoading, error } = useSearchQuery({ apiHostname, apiKey, catalogId, query: 'test', limit: 10, });