| 3741 |
stevensc |
1 |
import { useEffect, useState } from 'react';
|
|
|
2 |
|
|
|
3 |
import { useApi, useDebouncedSearchParam, usePagination } from '@shared/hooks';
|
|
|
4 |
import { addQuestion, editQuestion, deleteQuestion } from '@my-coach/services';
|
|
|
5 |
|
|
|
6 |
export function useQuestions() {
|
|
|
7 |
const [questions, setQuestions] = useState([]);
|
|
|
8 |
|
|
|
9 |
const { data, loading, hasMore, loadMore, applyFilters } = usePagination('/my-coach/questions');
|
|
|
10 |
|
|
|
11 |
const { data: addedQuestion, execute: executeAddQuestion } = useApi(addQuestion);
|
|
|
12 |
const { data: updatedQuestion, execute: executeEditQuestion } = useApi(editQuestion);
|
|
|
13 |
const { data: deletedQuestion, execute: executeDeleteQuestion } = useApi(deleteQuestion);
|
|
|
14 |
|
|
|
15 |
const {
|
|
|
16 |
inputValue: searchTerm,
|
|
|
17 |
setInputValue: setSearchTerm,
|
|
|
18 |
debouncedValue: debouncedSearchTerm
|
|
|
19 |
} = useDebouncedSearchParam('search');
|
|
|
20 |
|
|
|
21 |
const {
|
|
|
22 |
inputValue: searchCategory,
|
|
|
23 |
setInputValue: setSearchCategory,
|
|
|
24 |
debouncedValue: debouncedSearchCategory
|
|
|
25 |
} = useDebouncedSearchParam('category_id');
|
|
|
26 |
|
|
|
27 |
const clearFilters = () => {
|
|
|
28 |
setSearchTerm('');
|
|
|
29 |
setSearchCategory('');
|
|
|
30 |
};
|
|
|
31 |
|
|
|
32 |
useEffect(() => {
|
|
|
33 |
applyFilters({
|
|
|
34 |
search: debouncedSearchTerm,
|
|
|
35 |
category_id: debouncedSearchCategory
|
|
|
36 |
});
|
|
|
37 |
}, [debouncedSearchTerm, debouncedSearchCategory]);
|
|
|
38 |
|
|
|
39 |
useEffect(() => {
|
|
|
40 |
if (data) {
|
|
|
41 |
setQuestions(data);
|
|
|
42 |
}
|
|
|
43 |
}, [data]);
|
|
|
44 |
|
|
|
45 |
useEffect(() => {
|
|
|
46 |
if (addedQuestion) {
|
|
|
47 |
setQuestions([...questions, addedQuestion]);
|
|
|
48 |
}
|
|
|
49 |
}, [addedQuestion]);
|
|
|
50 |
|
|
|
51 |
useEffect(() => {
|
|
|
52 |
if (updatedQuestion) {
|
|
|
53 |
setQuestions(
|
|
|
54 |
questions.map((question) =>
|
|
|
55 |
question.id === updatedQuestion.id ? updatedQuestion : question
|
|
|
56 |
)
|
|
|
57 |
);
|
|
|
58 |
}
|
|
|
59 |
}, [updatedQuestion]);
|
|
|
60 |
|
|
|
61 |
useEffect(() => {
|
|
|
62 |
if (deletedQuestion) {
|
|
|
63 |
setQuestions(questions.filter((question) => question.id !== deletedQuestion.id));
|
|
|
64 |
}
|
|
|
65 |
}, [deletedQuestion]);
|
|
|
66 |
|
|
|
67 |
return {
|
|
|
68 |
questions,
|
|
|
69 |
loading,
|
|
|
70 |
hasMore,
|
|
|
71 |
search: searchTerm,
|
|
|
72 |
category: searchCategory,
|
|
|
73 |
loadMore,
|
|
|
74 |
applyFilters,
|
|
|
75 |
searchQuestion: setSearchTerm,
|
|
|
76 |
searchCategory: setSearchCategory,
|
|
|
77 |
clearFilters,
|
|
|
78 |
addQuestion: executeAddQuestion,
|
|
|
79 |
editQuestion: executeEditQuestion,
|
|
|
80 |
deleteQuestion: executeDeleteQuestion
|
|
|
81 |
};
|
|
|
82 |
}
|