2022-12-08 11:37:04 -08:00
|
|
|
import { useInfiniteQuery } from '@tanstack/react-query';
|
2022-08-10 05:38:49 -07:00
|
|
|
|
2022-12-08 11:37:04 -08:00
|
|
|
import { getNextLink } from 'soapbox/api';
|
2022-08-10 05:38:49 -07:00
|
|
|
import { useApi } from 'soapbox/hooks';
|
2022-12-08 11:37:04 -08:00
|
|
|
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();
|
|
|
|
|
2022-12-08 11:37:04 -08:00
|
|
|
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
|
|
|
|
2022-12-08 11:37:04 -08:00
|
|
|
const response = await api.get(uri, {
|
2022-08-10 05:38:49 -07:00
|
|
|
params: {
|
|
|
|
q,
|
2022-12-08 11:37:04 -08:00
|
|
|
limit: 10,
|
2022-08-10 05:38:49 -07:00
|
|
|
followers: true,
|
|
|
|
},
|
|
|
|
});
|
2022-12-08 11:37:04 -08:00
|
|
|
const { data } = response;
|
2022-08-10 05:38:49 -07:00
|
|
|
|
2022-12-08 11:37:04 -08:00
|
|
|
const link = getNextLink(response);
|
|
|
|
const hasMore = !!link;
|
|
|
|
|
|
|
|
return {
|
|
|
|
result: data,
|
|
|
|
link,
|
|
|
|
hasMore,
|
|
|
|
};
|
2022-08-10 05:38:49 -07:00
|
|
|
};
|
|
|
|
|
2022-12-08 11:37:04 -08:00
|
|
|
const queryInfo = useInfiniteQuery(['search', 'accounts', q], ({ pageParam }) => getAccountSearch(q, pageParam), {
|
2022-08-10 05:38:49 -07:00
|
|
|
keepPreviousData: true,
|
2022-12-08 11:37:04 -08:00
|
|
|
getNextPageParam: (config) => {
|
|
|
|
if (config.hasMore) {
|
|
|
|
return { link: config.link };
|
|
|
|
}
|
|
|
|
|
|
|
|
return undefined;
|
|
|
|
},
|
2022-08-10 05:38:49 -07:00
|
|
|
});
|
2022-12-08 11:37:04 -08:00
|
|
|
|
2022-12-12 10:10:39 -08:00
|
|
|
const data = flattenPages(queryInfo.data);
|
2022-12-08 11:37:04 -08:00
|
|
|
|
|
|
|
return {
|
|
|
|
...queryInfo,
|
|
|
|
data,
|
|
|
|
};
|
2022-08-10 05:38:49 -07:00
|
|
|
}
|