@@ -5,6 +5,7 @@ import ButtonGroup from "react-bootstrap/ButtonGroup";
5
5
import CreateQn from "./CreateQn" ;
6
6
import EditQn from "./EditQn" ;
7
7
import questionService from "../../services/questions"
8
+ import categoryService from "../../services/categories"
8
9
9
10
function Question ( ) {
10
11
const [ questions , setQuestions ] = useState ( [ ] ) ;
@@ -63,16 +64,44 @@ function Question() {
63
64
} ;
64
65
65
66
const handleDeleteConfirm = ( ) => {
66
- if ( questionToDelete ) {
67
- questionService . deleteQuestion ( questionToDelete )
68
- . then ( res => {
69
- console . log ( res ) ;
70
- setQuestions ( questions . filter ( question => question . _id !== questionToDelete ) ) ;
71
- handleCloseDelete ( ) ;
67
+ if ( ! questionToDelete ) return ;
68
+
69
+ // retrieve the question to get its categories before deleting
70
+ questionService . get ( questionToDelete )
71
+ . then ( ( question ) => {
72
+ const categories = question . data . category ;
73
+ console . log ( "question retrieved: " , question )
74
+ console . log ( `catgories of qn: ${ categories } ` )
75
+
76
+ // delete the question
77
+ questionService . deleteQuestion ( questionToDelete )
78
+ . then ( res => {
79
+ console . log ( res ) ;
80
+
81
+
82
+ setQuestions ( questions . filter ( q => q . _id !== questionToDelete ) ) ;
83
+ handleCloseDelete ( ) ;
84
+
85
+ // check each category to see if it should be deleted
86
+ categories . forEach ( async ( category ) => {
87
+ try {
88
+ const remainingQuestions = await questionService . getQuestionsByCategory ( category ) ;
89
+
90
+ // if no other questions have this category, delete the category
91
+ if ( remainingQuestions . length === 0 ) {
92
+ await categoryService . deleteCategory ( category ) ;
93
+ console . log ( `Category ${ category } deleted.` ) ;
94
+ }
95
+ } catch ( err ) {
96
+ console . error ( `Error processing category ${ category } :` , err ) ;
97
+ }
98
+ } ) ;
99
+ } )
100
+ . catch ( err => console . error ( "Error deleting question:" , err ) ) ;
72
101
} )
73
- . catch ( err => console . log ( err ) ) ;
74
- }
102
+ . catch ( err => console . error ( `Error fetching question data for ID ${ questionToDelete } :` , err ) ) ;
75
103
} ;
104
+
76
105
77
106
const renderQuestionsTable = ( questions ) => {
78
107
const sortedQuestions = [ ...questions ] . sort ( ( a , b ) => a . id - b . id )
0 commit comments