tooot/src/utils/queryHooks/tags.ts

66 lines
1.9 KiB
TypeScript
Raw Normal View History

2022-12-10 20:19:18 +01:00
import apiInstance, { InstanceResponse } from '@api/instance'
2022-11-20 16:14:08 +01:00
import { AxiosError } from 'axios'
import {
QueryFunctionContext,
2022-12-10 20:19:18 +01:00
useInfiniteQuery,
UseInfiniteQueryOptions,
2022-11-20 16:14:08 +01:00
useMutation,
UseMutationOptions,
useQuery,
UseQueryOptions
} from '@tanstack/react-query'
2022-12-10 20:19:18 +01:00
import { infinitePageParams } from './utils'
2022-11-20 16:14:08 +01:00
2022-12-10 20:19:18 +01:00
export type QueryKeyFollowedTags = ['FollowedTags']
const useFollowedTagsQuery = (
params: {
options?: Omit<
UseInfiniteQueryOptions<InstanceResponse<Mastodon.Tag[]>, AxiosError>,
'getPreviousPageParam' | 'getNextPageParam'
>
} | void
) => {
2022-11-20 16:14:08 +01:00
const queryKey: QueryKeyFollowedTags = ['FollowedTags']
2022-12-10 20:19:18 +01:00
return useInfiniteQuery(
2022-11-20 16:14:08 +01:00
queryKey,
async ({ pageParam }: QueryFunctionContext<QueryKeyFollowedTags>) => {
const params: { [key: string]: string } = { ...pageParam }
2022-12-10 20:19:18 +01:00
return await apiInstance<Mastodon.Tag[]>({ method: 'get', url: `followed_tags`, params })
2022-11-20 16:14:08 +01:00
},
2022-12-10 20:19:18 +01:00
{
...params?.options,
...infinitePageParams
}
2022-11-20 16:14:08 +01:00
)
}
2022-12-10 20:19:18 +01:00
export type QueryKeyTags = ['Tags', { tag: string }]
const queryFunction = async ({ queryKey }: QueryFunctionContext<QueryKeyTags>) => {
2022-11-20 16:14:08 +01:00
const { tag } = queryKey[1]
const res = await apiInstance<Mastodon.Tag>({ method: 'get', url: `tags/${tag}` })
return res.body
2022-11-20 16:14:08 +01:00
}
const useTagsQuery = ({
options,
...queryKeyParams
}: QueryKeyTags[1] & {
options?: UseQueryOptions<Mastodon.Tag, AxiosError>
}) => {
const queryKey: QueryKeyTags = ['Tags', { ...queryKeyParams }]
return useQuery(queryKey, queryFunction, options)
}
2022-12-10 20:19:18 +01:00
type MutationVarsAnnouncement = { tag: string; to: boolean }
const mutationFunction = async ({ tag, to }: MutationVarsAnnouncement) => {
return apiInstance<{}>({
method: 'post',
url: `tags/${tag}/${to ? 'follow' : 'unfollow'}`
})
2022-11-20 16:14:08 +01:00
}
const useTagsMutation = (options: UseMutationOptions<{}, AxiosError, MutationVarsAnnouncement>) => {
return useMutation(mutationFunction, options)
}
export { useFollowedTagsQuery, useTagsQuery, useTagsMutation }