1
+ import { useState } from "react" ;
1
2
import { Autocomplete , Chip , TextField } from "@mui/material" ;
2
3
import { createFilterOptions } from "@mui/material/Autocomplete" ;
3
4
import { categoryList } from "../../utils/constants" ;
4
5
5
6
interface QuestionCategoryAutoCompleteProps {
6
7
selectedCategories ?: string [ ] ;
7
- setSelectedCategories : ( value : string [ ] ) => void ;
8
+ setSelectedCategories : React . Dispatch < React . SetStateAction < string [ ] > > ;
8
9
}
9
10
10
11
const QuestionCategoryAutoComplete : React . FC < QuestionCategoryAutoCompleteProps > = ( {
@@ -14,6 +15,10 @@ const QuestionCategoryAutoComplete: React.FC<QuestionCategoryAutoCompleteProps>
14
15
// TODO
15
16
// Fetch category list from the server
16
17
18
+ // copy is created to ensure that Autocomplete rerenders when the selectedCategories change
19
+ const [ selectedCategoriesCopy , setSelectedCategoriesCopy ] = useState < string [ ] > (
20
+ selectedCategories || [ ]
21
+ ) ;
17
22
const filter = createFilterOptions < string > ( ) ;
18
23
19
24
return (
@@ -23,13 +28,16 @@ const QuestionCategoryAutoComplete: React.FC<QuestionCategoryAutoCompleteProps>
23
28
options = { categoryList }
24
29
size = "small"
25
30
sx = { { marginTop : 2 } }
26
- value = { selectedCategories }
31
+ value = { selectedCategoriesCopy }
27
32
onChange = { ( e , newCategoriesSelected ) => {
28
33
const newValue = newCategoriesSelected [ newCategoriesSelected . length - 1 ] ;
29
34
if ( typeof newValue === "string" && newValue . startsWith ( `Add: "` ) ) {
30
- categoryList . push ( newValue . slice ( 6 , - 1 ) ) ;
31
- setSelectedCategories ( [ ...newCategoriesSelected . slice ( 0 , - 1 ) , newValue . slice ( 6 , - 1 ) ] ) ;
35
+ const newCategory = newValue . slice ( 6 , - 1 ) ;
36
+ categoryList . push ( newCategory ) ;
37
+ setSelectedCategoriesCopy ( ( prev ) => [ ...prev , newCategory ] ) ;
38
+ setSelectedCategories ( ( prev ) => [ ...prev , newCategory ] ) ;
32
39
} else {
40
+ setSelectedCategoriesCopy ( newCategoriesSelected ) ;
33
41
setSelectedCategories ( newCategoriesSelected ) ;
34
42
}
35
43
} }
0 commit comments