Search code examples
javascriptreactjsaxiosmaterial-uiwarnings

How can I provide a value that resolves this Material UI warning?


I'm fetching API data (category names) from back-end (Node.js) to front-end (React). My goal, at the moment, is to populate a Select component from Material UI. For fetch API data, I'm using Express and Request on back-end; Axios on front-end. Apparently, it works, the Select component got a correct list of options but this console warning appeared:

Material-UI: You have provided an out-of-range value `` for the select component. Consider providing a value that matches one of the available options or ''. The available values are animal, career, celebrity, dev, explicit, fashion, food, history, money, movie, music, political, religion, science, sport, travel.

These referenced values are from the fetched API data but I don't know how to correct this. Any help is welcome. Here's my code:

export default function Home() {
  const classes = useStyles();
  const [list, setList] = useState([]);
  const [categoryName, setCategoryName] = useState([]);

  useEffect(() => {
    axios
      .get("/getCategories")
      .then((response) => {
        setList(response.data.categories);        
      })
      .catch((e) => {
        console.log(e.response.data);
      });
  }, []);

  const handleChange = (event) => {
    setCategoryName(event.target.value);    
  };

  return (
    <div className={classes.root}>      
      <FormControl>
        <InputLabel id="category-label">Category</InputLabel>
        <Select         
          labelId="category-label"
          id="category"
          value={categoryName}
          onChange={handleChange}
        >
          {list.map((item) => (
            <MenuItem key={item} value={item}>
              {item}
            </MenuItem>
          ))}
        </Select>
      </FormControl>
    </div>
  );
}

Solution

  • everything good but you just needs some changes before

    const [categoryName, setCategoryName] = useState([]);
    

    after

     const [categoryName, setCategoryName] = useState('');
    

    don't use categoryName default value as an array or the name(because of useEffect run after rendering. so the first time value not set after useEffect call your value set in your category list and it check if the value exists in the category list otherwise it will generate a warning), a warning means you add value(value={categoryName}) in the select that not in your list the best way using defaultValue option but anyway you just set your categoryName value as empty and you just learn about useEffect & how it's work https://stackblitz.com/edit/react-hmdhsf?file=src/home.js