Search code examples
material-uiautocompleteag-grid-react

Ag Grid React community Autocomplete with MUI, onChange event is not triggered and Inputchnge is triggered ,however the value does not getting updated


Trying to achieve autocomplete with MUI in aggrid react as community version does not have this feature, the issue is AutoComplete onchange event is not getting triggered so the value after selection goes blank. Suggest if I need to go for something else than MUI autocomplete.

//This is coldef
```` 
{
field: "currencyCode",
headerName: "Currency Code",
minWidth: 150,
editable: true,
cellEditor: AutoComplete,
cellEditorParams: {
  values: currency,
},
cellEditorPopup: true,
},
```` 
 ````    

//Autocomplete using MUI
import React, { useState, useEffect, forwardRef, useImperativeHandle } from 'react';
import { Autocomplete, TextField } from '@mui/material';

const CustomCAutoComplete = forwardRef((props, ref) => {
const [value, setValue] = useState(props.value || '');
const [inputValue, setInputValue] = useState('');

useEffect(() => {
 setValue(props.value || '');
}, [props.value]);
//triggers on change
const handleChange = (event, newValue) => {
 setValue(newValue);
 if (props.api) {
  props.api.stopEditing(false, newValue);
}
};
//triggers on type of each key
const handleInputChange = (event, newInputValue) => {
setInputValue(newInputValue);
};

useImperativeHandle(ref, () => ({
getValue: () => value,
}));

return (
<Autocomplete
  value={value}
  onChange={handleChange}
  inputValue={inputValue}
  onInputChange={handleInputChange}
  options={props.values}
  renderInput={(params) => <TextField {...params} />}
  freeSolo
 />
);
});

export default CustomCAutoComplete;
````

Solution

  • Ok, I figured out the issue. The problem is with the line api.stopEditing();. You are calling it immediately which is removing the cell editor before the state selectedValue is updated. So when the getValue in useImperativeHandle is called the value of the state selectedValue is empty and it is returning the empty string.

    Solution:

    Call the api.stopEditing() in useEffect hook after the state value has changed.

      useEffect(() => {
        if (value !== selectedValue) {
          api.stopEditing();
        }
      }, [selectedValue]);
    

    Full code for AutoCompleteEditor

    const AutoCompleteEditor = forwardRef((props: any, ref) => {
      const { value, api, column, node } = props;
      const [selectedValue, setSelectedValue] = useState(value || "");
    
      useEffect(() => {
        console.log("Value: " + selectedValue);
        if (value !== selectedValue) {
          api.stopEditing();
        }
      }, [selectedValue]);
    
      // ✅ Expose methods AG Grid needs
      useImperativeHandle(ref, () => ({
        getValue: () => selectedValue, // AG Grid will use this to get the final value
      }));
    
      const handleChange = (_: any, newValue: string | null) => {
        if (newValue) {
          setSelectedValue(newValue);
    
          // ✅ Update row data correctly
          api.applyTransaction({
            update: [{ ...node.data, [column.colId]: newValue }],
          });
        }
      };
    
      return (
        <Autocomplete
          options={currencyOptions}
          value={selectedValue}
          onChange={handleChange}
          renderInput={(params) => <TextField {...params} variant="standard" />}
          disableClearable
          autoFocus
        />
      );
    });
    

    Check the working Demo:

    Edit aggrid-autocomplete (forked)