reactjsreact-hooksmaterial-uimui-autocomplete

react- cleaning autocomplete generates an error


I have a form created with Material UI, I have a textfield that uses autocomplete which is filled with a useEffect that is responsible for bringing the data from the API to load the AUTOCOMPLETE.

The data is not saved.

Code

  const defaultProps={
    options:location.name,
    getOptionLabel: option =>  option.label + "-" + option.phone,
  };


  <Autocomplete
        style={{ width: 300 }}
        {...defaultProps}
        id="city"
        autoComplete                   
        onChange={(event, newVal)=>onChange({target:{name:"name",value: newVal.label }}
          )}
        renderInput={params => (
          <TextField {...params}   label="Country"  margin="normal" variant="outlined" inputProps={{
            ...params.inputProps,
          }}/>
        )}

What is causing that behavior?


Solution

  • It appears your problem in on the following line:

    onChange={(event, newVal)=>onTagsChange({target:{name:"label",value: newVal.label }}

    It may be related to newValue being null after clearing. You could add a protection such as:

    value: newVal || newVal.label

    Since it is not clear to me how you are using the resulting selection my suggested protection may not be appropriate.

    You may also want to take a look at their "controlled" example in the documentation (https://material-ui.com/components/autocomplete/#playground) in which they use the value attribute to control the AutoComplete:

    <Autocomplete
     {...defaultProps}
     id="controlled-demo"
     value={value}
     onChange={(event, newValue) => {
      setValue(newValue);
     }}
     renderInput={params => (
      <TextField {...params} label="controlled" margin="normal" fullWidth />
     )}
    />