简体   繁体   中英

Uncaught TypeError: Cannot read properties of undefined (reading 'name') | Material UI

I'm trying to view the fetched data on MUI Autocomplete, but I get this error I don't why, the stat is fetched from MongoDB and I'm just trying to view the name of the category as an option.

在此处输入图像描述

The Code:

export default function ChooseCat() {

  const [categories, setCats] = useState([]);

  useEffect(() => {
    const getCats = async () => {
      const res = await axios.get("/categories");
      setCats(res.data);
    };
    getCats();
  }, []);
  console.log(categories)

return(
    <div>
      <Autocomplete
        multiple
        id="tags-standard"
        options={categories}
        getOptionLabel={(c) => c.name}
        defaultValue={[categories[3]]}
        renderInput={(params) => (
          <TextField
            {...params}
            variant="standard"
            label="Multiple values"
            placeholder="Favorites"
          />
        )}
      />
  </div>
)
} 

This is how the data is showing in Mongodb在此处输入图像描述

you can add nullish coalescing operator (??) for options of Autocomplete. it's for situation when the options is empty or server response has error. one more thing, the options of Autocomplete should be arrays of object then you can set name property for options label.

export default function ChooseCat() {

  const [categories, setCats] = useState([]);

  useEffect(() => {
    const getCats = async () => {
      const res = await axios.get("/categories");
      setCats(res.data);
    };
    getCats();
  }, []);
  console.log(categories)

return(
    <div>
      <Autocomplete
        multiple
        id="tags-standard"
        options={categories ?? [] }
        getOptionLabel={(c) => c.name}
        defaultValue={[categories[3]]}
        renderInput={(params) => (
          <TextField
            {...params}
            variant="standard"
            label="Multiple values"
            placeholder="Favorites"
          />
        )}
      />
  </div>
)
} 

所以我添加了这个并且它起作用了getOptionLabel={option => (option ? option.name : "")}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM