53 lines
1.3 KiB
TypeScript
53 lines
1.3 KiB
TypeScript
|
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<MetadataPayload> => {
|
||
|
const response = await fetch(`/api/user/metadata`)
|
||
|
const data = await response.json()
|
||
|
return data
|
||
|
}
|
||
|
|
||
|
const fetchMutateMetadata = async (data: UpdateMetadataInput): Promise<void> => {
|
||
|
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 }
|