(app-desk) add useUpdateTeamAccess react-query hook

Add the hook useUpdateTeamAccess, it will be used to
change the role of a member.
This commit is contained in:
Anthony LC
2024-03-05 12:21:00 +01:00
committed by Anthony LC
parent 150258b5a4
commit 9be973a776
2 changed files with 69 additions and 0 deletions

View File

@@ -3,3 +3,4 @@ export * from './useCreateTeam';
export * from './useTeam';
export * from './useTeams';
export * from './useTeamsAccesses';
export * from './useUpdateTeamAccess';

View File

@@ -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<Access> => {
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<Access>;
};
type UseUpdateTeamAccess = Partial<Access>;
type UseUpdateTeamAccessOptions = UseMutationOptions<
Access,
APIError,
UseUpdateTeamAccess
>;
export const useUpdateTeamAccess = (options?: UseUpdateTeamAccessOptions) => {
const queryClient = useQueryClient();
return useMutation<Access, APIError, UpdateTeamAccessProps>({
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);
}
},
});
};