Files
protoc-frontend/src/hook/useSheetQueries.ts

129 lines
3.8 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import {
createSheet,
getSheetsByTemplate,
patchSheet,
type ApiSheet,
type GetSheetsOutput,
type PatchSheetInput,
} from '@/service/sheetApiService'
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
// Ключи для React Query
export const sheetKeys = {
all: ['sheets'] as const,
byTemplate: (templateId: string) =>
[...sheetKeys.all, 'template', templateId] as const,
detail: (sheetId: string) => [...sheetKeys.all, 'detail', sheetId] as const,
}
// Хук для получения листов по template_id с кешированием
export function useSheetsByTemplate(templateId: string | undefined) {
return useQuery({
queryKey: sheetKeys.byTemplate(templateId || ''),
queryFn: () => getSheetsByTemplate(templateId!),
enabled: !!templateId,
staleTime: 1 * 60 * 1000, // 1 минута для активных данных
gcTime: 5 * 60 * 1000, // 5 минут кеш
refetchOnWindowFocus: false, // Не перезапрашивать при фокусе окна
})
}
// Хук для создания листа
export function useCreateSheet() {
const queryClient = useQueryClient()
return useMutation({
mutationFn: createSheet,
onSuccess: (data, variables) => {
// Инвалидируем кеши после создания листа
queryClient.invalidateQueries({
queryKey: sheetKeys.byTemplate(variables.template_id),
})
queryClient.invalidateQueries({
queryKey: sheetKeys.all,
})
// Добавляем новый лист в кеш списка листов для шаблона
queryClient.setQueryData<GetSheetsOutput>(
sheetKeys.byTemplate(variables.template_id),
oldData => {
if (!oldData) return { sheets: [] }
const newSheet: ApiSheet = {
id: data.id,
name: variables.name,
cells: variables.cells,
template_id: variables.template_id,
created_at: new Date().toISOString(),
updated_at: new Date().toISOString(),
}
return {
sheets: [...oldData.sheets, newSheet],
}
}
)
},
})
}
// Хук для обновления листа
export function usePatchSheet() {
const queryClient = useQueryClient()
return useMutation({
mutationFn: ({
sheetId,
data,
}: {
sheetId: string
data: PatchSheetInput
}) => patchSheet(sheetId, data),
onSuccess: (result, variables) => {
// Обновляем конкретный лист в кеше
queryClient.setQueryData(
sheetKeys.detail(variables.sheetId),
(oldData: any) => {
if (!oldData?.sheet) return oldData
return {
sheet: {
...oldData.sheet,
...variables.data,
updated_at: new Date().toISOString(),
},
}
}
)
// Обновляем лист в списке листов для шаблона
const sheetDetail = queryClient.getQueryData(
sheetKeys.detail(variables.sheetId)
) as any
const templateId = sheetDetail?.sheet?.template_id
if (templateId) {
queryClient.setQueryData<GetSheetsOutput>(
sheetKeys.byTemplate(templateId),
oldData => {
if (!oldData) return oldData
return {
sheets: oldData.sheets.map(sheet =>
sheet.id === variables.sheetId
? {
...sheet,
name: variables.data.name || sheet.name,
cells: variables.data.cells || sheet.cells,
updated_at: new Date().toISOString(),
}
: sheet
),
}
}
)
}
},
})
}