hello everyone in the StackOverflow community, I wanna try to have a sidebar like amazon but I fail to have the same. As I see all data of my code is working very well I try it all with the console.log()
function. But the inverse happens when I try to use it in the component function it doesn’t work as I want. It doesn’t display the subcategories list under every header category. it returns this error:
Uncaught TypeError: Cannot read properties of undefined (reading ‘map’).
at CategoriesBar.js:69:1
This is my code:
import {useState, useEffect} from "react";
import List from '@mui/material/List';
import ListItem from '@mui/material/ListItem';
import ListItemText from '@mui/material/ListItemText';
import ListSubheader from '@mui/material/ListSubheader';
import {Link} from "react-router-dom";
import axios from "axios";
function CategoriesBar() {
let [subCategories, setSubCategories] = useState({});
let [dataCategories, setDataCategories] = useState([]);
const getCategories = async() => {
await axios.get("/api/categories")
.then(res => res.data)
.then(data => setDataCategories(data))
.catch(err => console.log(err));
};
const getSubCategories = async() => {
let newSub ={};
try {
if(dataCategories.length !== 0) {
dataCategories.forEach(async(category,i) => {
const response = await axios.get(`/api/subcategories/${category.id}`)
const {subcategories} = response.data;
let subName = subcategories.map(sub => sub.name);
newSub[category.name] = subName;
})
setSubCategories(newSub);
localStorage.setItem("subcategories", newSub);
} else {
return
}
}catch(err) {
console.log(err)
}
}
useEffect(()=> {
getCategories()
.then(()=> getSubCategories())
}, []);
console.log(subCategories)
return (
<div>
<div className="text-white font-bold bg-green-700 pt-2.5 pl-2 pb-2.5 pr-8 w-96 text-2xl">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" strokeWidth={1.5} stroke="currentColor" className="w-10 inline-block pr-2 ">
<path strokeLinecap="round" strokeLinejoin="round" d="M17.982 18.725A7.488 7.488 0 0012 15.75a7.488 7.488 0 00-5.982 2.975m11.963 0a9 9 0 10-11.963 0m11.963 0A8.966 8.966 0 0112 21a8.966 8.966 0 01-5.982-2.275M15 9.75a3 3 0 11-6 0 3 3 0 016 0z" />
</svg>
Hello, Sign In
</div>
<List sx={{
width: '100%',
maxWidth: 384,
bgColor: 'background.paper',
position: 'absolute',
overflowY: 'scroll',
height: '100%',
'& ul': { padding: 0 }
}}
subheader={<li />} >
{dataCategories.length !==0 && dataCategories.map(item => item.name).map((category, index) => (
<li key={index}>
<ul>
<ListSubheader sx={{fontWeight:"bold", color: "black", fontSize: 24, marginTop: 3}} >{category}</ListSubheader>
{subCategories[category].map((item, index) => (
<ListItem key={index}>
<ListItemText primary={item} />
</ListItem>
))}
</ul>
</li>
))}
</List>
</div>
)};
export default CategoriesBar;