Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Material UI Autocomplete component not showing values from react state

I am trying to get value from the state for materialUI's autocomplete component.

I am facing the following problem : -

Autocomplte working fine for selecting the value and with onChange function it saving it into the state too. But when I refresh my page/ re-render it is not showing value on the textfeild(from saved state):

<Autocomplete
    name={"TideLocation"}
    disabled={p.disabled}
    options={data_source}
    getOptionLabel={option => option.text}
    inputValue={this.state.tidelocation_searchtext}
    onChange={_this.handleUpdateTideLocationField}
    onNewRequest={_this.handleChangeTideLocation}
    onBlur={_this.handleBlurTideLocationField}
    onUpdateInput={_this.handleUpdateTideLocationField}
      renderInput={(params) => (
       <TextField className="autoCompleteTxt"{...params} label="Location" />
    )}
/>

I tried with the debugger and found its getting value in this.state.tidelocation_searchtext but failed to set it with params.

Thanks in advance !! Ps: I tried with defaultValue and search text nothing worked for me

following is my ONchangeFunction

  handleUpdateTideLocationField = (str, value) => {
        debugger
        this.setState({tidelocation_searchtext: value.text});
    }

after selecting a value,following value saved in sate :

tidelocation_searchtext: "Auckland"
like image 875
DevCo Avatar asked Apr 02 '26 12:04

DevCo


2 Answers

So I found the solution all by myself by doing research and several hit and try, following is the solution of my problem:

<Autocomplete
  name={"TideLocation"}
  disabled={p.disabled}
  options={data_source.map(option=>option.text)} 
  defaultValue={this.state.tidelocation_searchtext}
  onChange={_this.handleUpdateTideLocationField}
  onNewRequest={_this.handleChangeTideLocation}
  onBlur={_this.handleBlurTideLocationField}
  onUpdateInput={_this.handleUpdateTideLocationField}
  renderInput={(params) => (
  <TextField className="autoCompleteTxt"{...params} label="Location" />
 )}
/>

Basically I was doing the following things wrong :

1.There is no need of using input inputValue={this.state.tidelocation_searchtext}& getOptionLabel={option => option.text}

2.as my data is in object form I have to convert it into a string so default value can match this from the state value options={data_source.map(option=>option.text)}

Thank you all for your valuable support and solution !!

like image 132
DevCo Avatar answered Apr 04 '26 00:04

DevCo


Removing inputValue has worked for me, even when passing object as options.

Using: "@material-ui/core": "^4.12.3"

like image 20
Hafiz Temuri Avatar answered Apr 04 '26 01:04

Hafiz Temuri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!