@@ -61,7 +61,10 @@ function EditQn({ question, handleClose, editQuestion }) {
61
61
console . log ( `newCategories are ${ newCategories } ` ) ;
62
62
63
63
categoryService . createCategories ( newCategories )
64
- . then ( result => console . log ( result . data ) )
64
+ . then ( result => {
65
+ console . log ( result . data )
66
+ window . dispatchEvent ( new Event ( "categoryChange" ) ) ;
67
+ } )
65
68
. catch ( e => {
66
69
if ( e . response && e . response . status === 400 ) {
67
70
setError ( e . response . data . error ) ;
@@ -71,7 +74,26 @@ function EditQn({ question, handleClose, editQuestion }) {
71
74
72
75
questionService . updateQuestion ( question . _id , updatedQuestion )
73
76
. then ( result => {
74
-
77
+ const initialCategories = question . category ;
78
+ const categoriesRemoved = initialCategories . filter ( item => ! categories . includes ( item ) ) ;
79
+
80
+ // check each category to see if it should be deleted
81
+ categoriesRemoved . forEach ( async ( category ) => {
82
+ try {
83
+ const remainingQuestions = await questionService . getQuestionsByCategory ( category ) ;
84
+
85
+ // if no other questions have this category, delete the category
86
+ if ( remainingQuestions . length === 0 ) {
87
+ await categoryService . deleteCategory ( category ) ;
88
+ console . log ( `Category ${ category } deleted.` ) ;
89
+ // dispatch the event here
90
+ window . dispatchEvent ( new Event ( "categoryChange" ) ) ;
91
+ }
92
+ } catch ( err ) {
93
+ console . error ( `Error processing category ${ category } :` , err ) ;
94
+ }
95
+ } ) ;
96
+
75
97
editQuestion ( question . _id , updatedQuestion ) ;
76
98
console . log ( 'Question edited successfully:' , result )
77
99
handleClose ( ) ;
0 commit comments