Skip to content
Advertisement

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.

enter image description here

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 enter image description here

Advertisement

Answer

So I added this and it worked getOptionLabel={option => (option ? option.name : "")}

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement