Mui Autocomplete – onChange is not triggered when adding option programmatically

Here is the component:

export const TagInput = (props: Props) => {

  let valueBackup = []
  const [value, setValue] = useState<Array<string>>([])
  const [searchTerm, setSearchTerm] = useContext(SearchContext)

  useEffect(() => {
    if (searchTerm != "") {
      setValue(prev => [...prev, searchTerm])
      valueBackup = value
    }
  }, [searchTerm])

  return (
    <div>
      <Autocomplete
        multiple
        value={value}
        id="tag-dropdown"
        sx={{maxWidth: 300, marginTop: '30px'}}
        options={props.tags}
        getOptionLabel={(option) => option}
        filterSelectedOptions
        renderInput={(params) => (
          <TextField
            {...params}
            placeholder="Tags..."
          />
        )}
        onChange={(_, value: Array<string>) => {
          console.log("THIS SHOULD BE PRINTED")
          setValue(value)
          return props.onChange(value)
        }}
      />
    </div>
  )
}

there is another component which just sets searchTerm variable. I’m expecting it to execute the piece of code inside onChange handler when searchTerm is changed and value variable is updated (value is its previous value + searchTerm), but it’s only being executed after I remove already selected options from Autocomplete. How can I solve that or is there any better ways to update selected options in MUI Autocomplete?

Leave a Comment