From a851720441a5a9eb83557f0ecc6e6961251f4d89 Mon Sep 17 00:00:00 2001 From: Anthony LC Date: Fri, 17 May 2024 22:38:47 +0200 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8(frontend)=20create=20useUpdatePad=20r?= =?UTF-8?q?eact=20query=20hook?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Create a react query hook to update a pad. PATCH /documents/:id --- .../features/pads/pad/api/useUpdatePad.tsx | 45 +++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 src/frontend/apps/impress/src/features/pads/pad/api/useUpdatePad.tsx diff --git a/src/frontend/apps/impress/src/features/pads/pad/api/useUpdatePad.tsx b/src/frontend/apps/impress/src/features/pads/pad/api/useUpdatePad.tsx new file mode 100644 index 00000000..40212921 --- /dev/null +++ b/src/frontend/apps/impress/src/features/pads/pad/api/useUpdatePad.tsx @@ -0,0 +1,45 @@ +import { useMutation, useQueryClient } from '@tanstack/react-query'; + +import { APIError, errorCauses, fetchAPI } from '@/api'; +import { Pad } from '@/features/pads'; + +export type PadParams = Pick & + Partial>; + +export const updatePad = async ({ id, ...params }: PadParams): Promise => { + const response = await fetchAPI(`documents/${id}/`, { + method: 'PATCH', + body: JSON.stringify({ + ...params, + }), + }); + + if (!response.ok) { + throw new APIError('Failed to update the pad', await errorCauses(response)); + } + + return response.json() as Promise; +}; + +interface UpdatePadProps { + onSuccess?: (data: Pad) => void; + listInvalideQueries?: string[]; +} + +export function useUpdatePad({ + onSuccess, + listInvalideQueries, +}: UpdatePadProps = {}) { + const queryClient = useQueryClient(); + return useMutation({ + mutationFn: updatePad, + onSuccess: (data) => { + listInvalideQueries?.forEach((queryKey) => { + void queryClient.invalidateQueries({ + queryKey: [queryKey], + }); + }); + onSuccess?.(data); + }, + }); +}