The scenario is when user save the new category, the Category dropdown should be re-rendered with new value. Unfortunately this is not happening.
I tried two approaches:
- When the dependency array is set to category variable. In this case, the call to fetch categories is infinite as shown in below image.
useEffect(() => {
const fetchCategoryList = async () => {
const data = await categoryApi.getAllDD();
setCategory(data);
};
fetchCategoryList();
}, [category]);
- When the dependency array is set to category.length variable. In this case, the useEffect does not get call at all.
const [category, setCategory] = useState([]);
..
..
..
useEffect(() => {
const fetchCategoryList = async () => {
const data = await categoryApi.getAllDD();
setCategory(data);
};
fetchCategoryList();
}, [category.length]);
<Autocomplete
disablePortal
id="ddCategory"
getOptionLabel={(option) => option.name}
getOptionKey={(option) => option.id}
options={category}
sx={{ width: 300 }}
renderInput={(params) => (
<TextField {...params} label="Parent Category" />
)}
size="small"
onChange={handleOnAutoCompleteInputChange}
/>
.
.
.
const handleOnAutoCompleteInputChange = (
e: React.SyntheticEvent,
value: any,
reason: string
) => {
setFormData((prevFormData) => ({
...prevFormData,
parentId: value?.id,
}));
};
Any idea why this is happening?
>Solution :
Instead of run fetchCategoryList on useEffect hook, you should run this function after click save button, for example:
const handleClick = async()=>{
// make request for save category or whatever you need to do
const response = await request()
// when we have response,then we ask for new category list
if( res){
const data = await fetchCategoryList();
data && setCategoryList(data);
}
}

