@@ -61,7 +61,10 @@ function EditQn({ question, handleClose, editQuestion }) {
6161 console . log ( `newCategories are ${ newCategories } ` ) ;
6262
6363 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+ } )
6568 . catch ( e => {
6669 if ( e . response && e . response . status === 400 ) {
6770 setError ( e . response . data . error ) ;
@@ -71,7 +74,26 @@ function EditQn({ question, handleClose, editQuestion }) {
7174
7275 questionService . updateQuestion ( question . _id , updatedQuestion )
7376 . 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+
7597 editQuestion ( question . _id , updatedQuestion ) ;
7698 console . log ( 'Question edited successfully:' , result )
7799 handleClose ( ) ;
0 commit comments