0

I have a problem with Autocomplete component. He works well, until I need to clear my selection (i.e. I changed my mind and want to unselect and leave empty field) before submitting form and make state empty. In documentation examples works fine with this task, but in my code it doesn't work.

Here my code:

<Autocomplete 
   classes={{
      root: classes.root
   }}
   style={{padding: 0}}
   options={positionArr} 
   getOptionLabel={(option) => option.name}
   renderInput={(params) => (
      <TextField
         {...params}
         className={`inputPadding`}
         classes={{root: classes.labelRoot}}
         label={t('position')}
         variant="outlined"
         helperText={t('optional')}
      />
   )}
   getOptionSelected={(opt, val) => opt === val}
   value={positionObjTwo}
   onChange={(e, val) => {val && setPositionObjTwo(val)}}
/>

positionArr looks like:

[
   {
      id: 1,
      name: 'AB'
   },
   {
      id: 2,
      name: 'AB/2OFF'
   },
   ...
]
2
  • Do you get an error when you click the clear button icon? Commented Dec 7, 2020 at 17:20
  • no, nothing, actually it clear input, but if I click outside input value appear again Commented Dec 7, 2020 at 17:21

1 Answer 1

2

When val is "" it won't call setPositionObjTwo(val) in onChange={(e, val) => {val && setPositionObjTwo(val)}}

"" evaluates to false so the second part of && is not executed. You could fix by changing the line to

onChange={(e, val) => {(val || val == "") && setPositionObjTwo(val)}} OR onChange={(e, val) => {setPositionObjTwo(val)}}

Sign up to request clarification or add additional context in comments.

4 Comments

"" shouldn't evaluate to false. When I do this in my browser console, it evaluates to the string. ``` const str = "" str && true "" ```
@technicallynick Try "" == false. (It should return true) Maybe it is different in the browser console.
My understanding was that evaluations in && was more strict (===) than ==
I think all truthy evaluations in javascript use == unless you explicitly use ===.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.