52 lines
1.5 KiB
TypeScript
52 lines
1.5 KiB
TypeScript
import { Survey, surveyApi } from '@/api/survey'
|
|
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
|
|
|
export function useServey(id?: number) {
|
|
const queryClient = useQueryClient()
|
|
|
|
const { data: surveyList, isLoading: isLoadingSurveyList } = useQuery({
|
|
queryKey: ['survey', 'list'],
|
|
queryFn: () => surveyApi.getList(),
|
|
})
|
|
|
|
const { data: surveyDetail, isLoading: isLoadingSurveyDetail } = useQuery({
|
|
queryKey: ['survey', id],
|
|
queryFn: () => surveyApi.getDetail(id),
|
|
enabled: !!id,
|
|
})
|
|
|
|
const { mutate: createSurvey, isPending: isCreatingSurvey } = useMutation({
|
|
mutationFn: (survey: Survey) => surveyApi.create(survey),
|
|
onSuccess: () => {
|
|
queryClient.invalidateQueries({ queryKey: ['survey', 'list'] })
|
|
},
|
|
})
|
|
|
|
const { mutate: updateSurvey, isPending: isUpdatingSurvey } = useMutation({
|
|
mutationFn: (survey: Survey) => surveyApi.update(survey.id, survey),
|
|
onSuccess: () => {
|
|
queryClient.invalidateQueries({ queryKey: ['survey', 'list'] })
|
|
},
|
|
})
|
|
|
|
const { mutate: deleteSurvey, isPending: isDeletingSurvey } = useMutation({
|
|
mutationFn: (id: number) => surveyApi.delete(id),
|
|
onSuccess: () => {
|
|
queryClient.invalidateQueries({ queryKey: ['survey', 'list'] })
|
|
},
|
|
})
|
|
|
|
return {
|
|
surveyList: surveyList ?? [],
|
|
surveyDetail: surveyDetail ?? {},
|
|
isLoadingSurveyList,
|
|
isLoadingSurveyDetail,
|
|
isCreatingSurvey,
|
|
isUpdatingSurvey,
|
|
isDeletingSurvey,
|
|
createSurvey,
|
|
updateSurvey,
|
|
deleteSurvey,
|
|
}
|
|
}
|