Skip to content

Instantly share code, notes, and snippets.

@eddievlagea
Created March 2, 2023 14:09
Show Gist options
  • Save eddievlagea/998c54546e8a7710dd604e26f61a4b2f to your computer and use it in GitHub Desktop.
Save eddievlagea/998c54546e8a7710dd604e26f61a4b2f to your computer and use it in GitHub Desktop.
useSearch.ts
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 };
}
@eddievlagea
Copy link
Author

const { data, isLoading, error } = useSearchQuery({ apiHostname, apiKey, catalogId, query: 'test', limit: 10, });

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment