bigbuffet-rw/app/soapbox/queries/search.ts

52 lines
1.2 KiB
TypeScript
Raw Normal View History

import { useInfiniteQuery } from '@tanstack/react-query';
2022-08-10 05:38:49 -07:00
import { getNextLink } from 'soapbox/api';
2022-08-10 05:38:49 -07:00
import { useApi } from 'soapbox/hooks';
import { Account } from 'soapbox/types/entities';
2022-12-12 10:10:39 -08:00
import { flattenPages, PaginatedResult } from 'soapbox/utils/queries';
2022-08-10 05:38:49 -07:00
export default function useAccountSearch(q: string) {
const api = useApi();
const getAccountSearch = async(q: string, pageParam: { link?: string }): Promise<PaginatedResult<Account>> => {
const nextPageLink = pageParam?.link;
const uri = nextPageLink || '/api/v1/accounts/search';
2022-08-10 05:38:49 -07:00
const response = await api.get(uri, {
2022-08-10 05:38:49 -07:00
params: {
q,
limit: 10,
2022-08-10 05:38:49 -07:00
followers: true,
},
});
const { data } = response;
2022-08-10 05:38:49 -07:00
const link = getNextLink(response);
const hasMore = !!link;
return {
result: data,
link,
hasMore,
};
2022-08-10 05:38:49 -07:00
};
const queryInfo = useInfiniteQuery(['search', 'accounts', q], ({ pageParam }) => getAccountSearch(q, pageParam), {
2022-08-10 05:38:49 -07:00
keepPreviousData: true,
getNextPageParam: (config) => {
if (config.hasMore) {
return { link: config.link };
}
return undefined;
},
2022-08-10 05:38:49 -07:00
});
2022-12-12 10:10:39 -08:00
const data = flattenPages(queryInfo.data);
return {
...queryInfo,
data,
};
2022-08-10 05:38:49 -07:00
}