import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query' import { toast } from 'react-hot-toast' import { patch } from 'lib/common/fetch' import { API_URL } from 'lib/constants' import { ResponseError } from 'types' import { projectKeys } from './keys' export type ProjectUpdateVariables = { ref: string name: string } export type ProjectUpdateResponse = { id: number ref: string name: string } export async function updateProject({ ref, name }: ProjectUpdateVariables) { const response = await patch(`${API_URL}/projects/${ref}`, { name }) if (response.error) throw response.error return response as ProjectUpdateResponse } type ProjectUpdateData = Awaited> export const useProjectUpdateMutation = ({ onSuccess, onError, ...options }: Omit< UseMutationOptions, 'mutationFn' > = {}) => { const queryClient = useQueryClient() return useMutation( (vars) => updateProject(vars), { async onSuccess(data, variables, context) { await queryClient.invalidateQueries(projectKeys.list()), await onSuccess?.(data, variables, context) }, async onError(data, variables, context) { if (onError === undefined) { toast.error(`Failed to update project: ${data.message}`) } else { onError(data, variables, context) } }, ...options, } ) }