Value type for Material UI's Select component

Viewed 1826

I am using Material UI's Select component (which is like a drop down menu) like this:

const [criteria, setCriteria] = useState('');
...
  let ShowUsers = () => {
    console.log('Working criteria', typeof(criteria));
    const where: UserFilter = {};
    if (criteria == '1') {
      loadUsers({
        variables: {
          where: where,
        },
      });
    }

    if (criteria == '2') {
      if (searchItem) {
        where.firstName_contains = searchItem;
        loadUsers({
          variables: {
           where: where,
          },
        });
      }
    }
}
...
return(
        <Select
          value={criteria}
          onChange={event => setCriteria(event.target.value as string)}
          //onChange={event => setCriteria(event.target.value)}
          displayEmpty>
          <MenuItem disabled value="">
            <em>Search By</em>
          </MenuItem>
          <MenuItem value={1}>All</MenuItem>
          <MenuItem value={2}>First Name</MenuItem>
          </Select>

        <Button onClick={() => ShowUsers()}>Search
        </Button>
)

Currently this gives me a warning that

Expected '===' and instead saw '=='  eqeqeq

To investigate this, I tried to print out the typeof(criteria) in the showUsers function. The type is number.

Hence, I changed (criteria === 1) etc. But then it gives an error that This condition will always return 'false' since the types 'string' and 'number' have no overlap.ts. But both are already numbers so I don't quite understand this.

Additionally, I also tried changing things like this:

const [criteria, setCriteria] = useState<number>();
..
onChange={event => setCriteria(Number(event.target.value))}

However, then I get new warnings that:

you have provided an out-of-range value `undefined` for the select component.
Consider providing a value that matches one of the available options or ''.
The available values are ``, `1`, `2`.
Warning: A component is changing an uncontrolled input of type hidden to be controlled. Input elements should not switch from uncontrolled to controlled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component. 

and if I simply use criteria === '1' without changing anything else, the conditions are never made true even when they should be.

Where am I going wrong? Probably something minor.

1 Answers

I have a suggestion. First of all, you could try using switch instead of if (criteria == '1') { Switch should be able to help you avoid this problem if you use it like this: switch (Number(criteria)) {

This would help you set default value as well that would help you avoid this error: you have provided an out-of-range value undefined for the select component.

Related