From 9be973a776cfc22215e2c395f185bb0dbdf8d6c9 Mon Sep 17 00:00:00 2001 From: Anthony LC Date: Tue, 5 Mar 2024 12:21:00 +0100 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8(app-desk)=20add=20useUpdateTeamAccess?= =?UTF-8?q?=20react-query=20hook?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add the hook useUpdateTeamAccess, it will be used to change the role of a member. --- .../apps/desk/src/features/teams/api/index.ts | 1 + .../features/teams/api/useUpdateTeamAccess.ts | 68 +++++++++++++++++++ 2 files changed, 69 insertions(+) create mode 100644 src/frontend/apps/desk/src/features/teams/api/useUpdateTeamAccess.ts diff --git a/src/frontend/apps/desk/src/features/teams/api/index.ts b/src/frontend/apps/desk/src/features/teams/api/index.ts index 5b969f5..a5dd14a 100644 --- a/src/frontend/apps/desk/src/features/teams/api/index.ts +++ b/src/frontend/apps/desk/src/features/teams/api/index.ts @@ -3,3 +3,4 @@ export * from './useCreateTeam'; export * from './useTeam'; export * from './useTeams'; export * from './useTeamsAccesses'; +export * from './useUpdateTeamAccess'; diff --git a/src/frontend/apps/desk/src/features/teams/api/useUpdateTeamAccess.ts b/src/frontend/apps/desk/src/features/teams/api/useUpdateTeamAccess.ts new file mode 100644 index 0000000..826ccf3 --- /dev/null +++ b/src/frontend/apps/desk/src/features/teams/api/useUpdateTeamAccess.ts @@ -0,0 +1,68 @@ +import { + UseMutationOptions, + useMutation, + useQueryClient, +} from '@tanstack/react-query'; + +import { APIError, errorCauses, fetchAPI } from '@/api'; + +import { Access, Role } from './types'; +import { KEY_TEAM } from './useTeam'; +import { KEY_LIST_TEAM_ACCESSES } from './useTeamsAccesses'; + +interface UpdateTeamAccessProps { + teamId: string; + accessId: string; + role: Role; +} + +export const updateTeamAccess = async ({ + teamId, + accessId, + role, +}: UpdateTeamAccessProps): Promise => { + const response = await fetchAPI(`teams/${teamId}/accesses/${accessId}/`, { + method: 'PATCH', + body: JSON.stringify({ + role, + }), + }); + + if (!response.ok) { + throw new APIError('Failed to update role', await errorCauses(response)); + } + + return response.json() as Promise; +}; + +type UseUpdateTeamAccess = Partial; + +type UseUpdateTeamAccessOptions = UseMutationOptions< + Access, + APIError, + UseUpdateTeamAccess +>; + +export const useUpdateTeamAccess = (options?: UseUpdateTeamAccessOptions) => { + const queryClient = useQueryClient(); + return useMutation({ + mutationFn: updateTeamAccess, + ...options, + onSuccess: (data, variables, context) => { + void queryClient.invalidateQueries({ + queryKey: [KEY_LIST_TEAM_ACCESSES], + }); + void queryClient.invalidateQueries({ + queryKey: [KEY_TEAM], + }); + if (options?.onSuccess) { + options.onSuccess(data, variables, context); + } + }, + onError: (error, variables, context) => { + if (options?.onError) { + options.onError(error, variables, context); + } + }, + }); +};