import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query' export type MetadataPayload = { metadata: { first_name: string last_name: string patreon: { entitledTiers: string[], lifetimeSupportCents: number, currentlyEntitledSupportCents: number }, isUsernamePublic: boolean } } export type UpdateMetadataInput = { isUsernamePublic: boolean } const fetchMetadata = async (): Promise => { const response = await fetch(`/api/user/metadata`) const data = await response.json() return data } const fetchMutateMetadata = async (data: UpdateMetadataInput): Promise => { const res = await fetch('/api/user/metadata', { method: 'POST', body: JSON.stringify({ isUsernamePublic: data.isUsernamePublic }) }) if (!res.ok) throw new Error(`failed to fetchMutateMetadata. ${res.status} ${res.statusText}`); } const useMetadata = () => { return useQuery({ queryKey: ['user/metadata'], queryFn: () => fetchMetadata() }) } const useMutateMetadata = () => { const queryClient = useQueryClient() return useMutation({ mutationFn: (data: UpdateMetadataInput) => fetchMutateMetadata(data), onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['user/metadata'] }) } }) } export { useMetadata, fetchMetadata, useMutateMetadata }