Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

useEffect is not working for Autoselect Dropdown

The scenario is when user save the new category, the Category dropdown should be re-rendered with new value. Unfortunately this is not happening.

enter image description here

I tried two approaches:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  1. 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]);

enter image description here

  1. 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);
    }
  }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading