bigbuffet-rw/packages/pl-hooks/lib/hooks/search/use-search.ts
marcin mikołajczak 423c9f1fc8 pl-hooks: do not import from /main
Signed-off-by: marcin mikołajczak <git@mkljczk.pl>
2024-10-28 23:49:17 +01:00

97 lines
2.8 KiB
TypeScript

import { useInfiniteQuery } from '@tanstack/react-query';
import { usePlHooksApiClient } from 'pl-hooks/contexts/api-client';
import { usePlHooksQueryClient } from 'pl-hooks/contexts/query-client';
import { importEntities } from 'pl-hooks/importer';
import type { SearchParams, Tag } from 'pl-api';
import type { PaginationParams } from 'pl-api/dist/params/common';
const useSearchAccounts = (
query: string,
params?: Omit<SearchParams, keyof PaginationParams | 'type' | 'offset'>,
) => {
const queryClient = usePlHooksQueryClient();
const { client } = usePlHooksApiClient();
const searchQuery = useInfiniteQuery({
queryKey: ['search', 'accounts', query, params],
queryFn: ({ pageParam }) => client.search.search(query!, {
...params,
offset: pageParam ? data?.length : 0,
type: 'accounts',
}).then(({ accounts }) => {
importEntities({ accounts });
return accounts.map(({ id }) => id);
}),
enabled: !!query?.trim(),
initialPageParam: [''],
getNextPageParam: (page) => page.length ? page : undefined,
}, queryClient);
const data: Array<string> | undefined = searchQuery.data?.pages.flat();
return {
...searchQuery,
data,
};
};
const useSearchStatuses = (
query: string,
params?: Omit<SearchParams, keyof PaginationParams | 'type' | 'offset'>,
) => {
const queryClient = usePlHooksQueryClient();
const { client } = usePlHooksApiClient();
const searchQuery = useInfiniteQuery({
queryKey: ['search', 'statuses', query, params],
queryFn: ({ pageParam }) => client.search.search(query, {
...params,
offset: pageParam ? data?.length : 0,
type: 'statuses',
}).then(({ statuses }) => {
importEntities({ statuses });
return statuses.map(({ id }) => id);
}),
enabled: !!query?.trim(),
initialPageParam: [''],
getNextPageParam: (page) => page.length ? page : undefined,
}, queryClient);
const data: Array<string> | undefined = searchQuery.data?.pages.flat();
return {
...searchQuery,
data,
};
};
const useSearchHashtags = (
query: string,
params?: Omit<SearchParams, keyof PaginationParams | 'type' | 'offset'>,
) => {
const queryClient = usePlHooksQueryClient();
const { client } = usePlHooksApiClient();
const searchQuery = useInfiniteQuery({
queryKey: ['search', 'hashtags', query, params],
queryFn: ({ pageParam }) => client.search.search(query, {
...params,
offset: pageParam ? data?.length : 0,
type: 'hashtags',
}).then(({ hashtags }) => hashtags as Array<Tag>),
enabled: !!query?.trim(),
initialPageParam: [{}],
getNextPageParam: (page) => page.length ? page : undefined,
}, queryClient);
const data: Array<Tag> | undefined = searchQuery.data?.pages.flat();
return {
...searchQuery,
data,
};
};
export { useSearchAccounts, useSearchStatuses, useSearchHashtags };