-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathtest-queries.ts
More file actions
72 lines (64 loc) · 2.23 KB
/
test-queries.ts
File metadata and controls
72 lines (64 loc) · 2.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import { addTest, deleteTest, editTest, getTests } from '../api/api';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { Test } from '../../../../../data/types/Trainee';
import { testsQueryKeys } from './keys';
/**
* Hook to add a test to a trainee.
* @param {string} traineeId the id of the trainee to add the test to.
* @param {Test} test the test to add.
*/
export const useAddTest = (traineeId: string) => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (test: Test) => addTest(traineeId, test),
onSuccess: async () => {
await queryClient.invalidateQueries({ queryKey: testsQueryKeys.list(traineeId) });
},
});
};
/**
* Hook to get the tests of a trainee.
* @param {string} traineeId the id of the trainee to get the tests from.
* @returns {UseQueryResult<Test[], Error>} the tests of the trainee.
*/
export const useGetTests = (traineeId: string) => {
return useQuery({
queryKey: testsQueryKeys.list(traineeId),
queryFn: async () => {
const data = await getTests(traineeId);
return orderTestsByDateDesc(data);
},
enabled: !!traineeId,
refetchOnWindowFocus: false,
});
};
/**
* Hook to delete a test from a trainee.
* @param {string} traineeId the id of the trainee to delete the test from.
* @param {string} testId the id of the test to delete.
* */
export const useDeleteTest = (traineeId: string) => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (testId: string) => deleteTest(traineeId, testId),
onSuccess: async () => {
await queryClient.invalidateQueries({ queryKey: testsQueryKeys.list(traineeId) });
},
});
};
/**
* Hook to edit a test of a trainee.
* @param {string} traineeId the id of the trainee to edit the test of.
*/
export const useEditTest = (traineeId: string) => {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (test: Test) => editTest(traineeId, test),
onSuccess: async () => {
await queryClient.invalidateQueries({ queryKey: testsQueryKeys.list(traineeId) });
},
});
};
const orderTestsByDateDesc = (data: Test[]): Test[] => {
return data.sort((a, b) => new Date(b.date).getTime() - new Date(a.date).getTime());
};