74 lines
2.3 KiB
TypeScript
74 lines
2.3 KiB
TypeScript
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
|
import { fetchActiveSession, createSession, endSession, fetchSessions, deleteSession, updateSession } from '../api/client';
|
|
import type { SleepSessionRead } from '../types';
|
|
|
|
export function useSleepSession() {
|
|
const queryClient = useQueryClient();
|
|
|
|
const activeSessionQuery = useQuery<SleepSessionRead | null>({
|
|
queryKey: ['activeSession'],
|
|
queryFn: fetchActiveSession,
|
|
refetchInterval: 30000, // Poll every 30 seconds
|
|
});
|
|
|
|
const createMutation = useMutation({
|
|
mutationFn: createSession,
|
|
onSuccess: () => {
|
|
queryClient.invalidateQueries({ queryKey: ['activeSession'] });
|
|
queryClient.invalidateQueries({ queryKey: ['sessions'] });
|
|
},
|
|
});
|
|
|
|
const endMutation = useMutation({
|
|
mutationFn: ({ sessionId, endTime }: { sessionId: number; endTime: string }) =>
|
|
endSession(sessionId, { end_time: endTime }),
|
|
onSuccess: () => {
|
|
queryClient.invalidateQueries({ queryKey: ['activeSession'] });
|
|
queryClient.invalidateQueries({ queryKey: ['sessions'] });
|
|
},
|
|
});
|
|
|
|
return {
|
|
activeSession: activeSessionQuery.data,
|
|
isLoading: activeSessionQuery.isLoading,
|
|
isFetching: activeSessionQuery.isFetching,
|
|
createSession: createMutation.mutateAsync,
|
|
endSession: endMutation.mutateAsync,
|
|
isCreating: createMutation.isPending,
|
|
isEnding: endMutation.isPending,
|
|
};
|
|
}
|
|
|
|
export function useSessions() {
|
|
const queryClient = useQueryClient();
|
|
|
|
const sessionsQuery = useQuery({
|
|
queryKey: ['sessions'],
|
|
queryFn: () => fetchSessions(),
|
|
});
|
|
|
|
const deleteMutation = useMutation({
|
|
mutationFn: deleteSession,
|
|
onSuccess: () => {
|
|
queryClient.invalidateQueries({ queryKey: ['sessions'] });
|
|
},
|
|
});
|
|
|
|
const updateMutation = useMutation({
|
|
mutationFn: ({ sessionId, payload }: { sessionId: number; payload: import('../types').SleepSessionUpdate }) =>
|
|
updateSession(sessionId, payload),
|
|
onSuccess: () => {
|
|
queryClient.invalidateQueries({ queryKey: ['sessions'] });
|
|
},
|
|
});
|
|
|
|
return {
|
|
sessions: sessionsQuery.data?.sessions || [],
|
|
total: sessionsQuery.data?.total || 0,
|
|
isLoading: sessionsQuery.isLoading,
|
|
isDeleting: deleteMutation.isPending,
|
|
deleteSession: deleteMutation.mutateAsync,
|
|
updateSession: updateMutation.mutateAsync,
|
|
};
|
|
}
|