coreui-free-react-admin-template
coreui-free-react-admin-template copied to clipboard
Dynamic Menu
I am trying to populate _nav with data coming from my API. I have been scratching my head on this for a while and wanted to see if anyone could shed some light. Please see code below. It breaks when the sub items are being called by the subNav function.
function subNav(parentID) {
axios.get('api/sql', {
params: {
table: 'main_menu'
}
})
.then(response => {
response.data.map((elements) => {
if (elements.parentID == parentID){
var type = 'CNavItem'
const subnav = [{
component: navtype[type],
name: elements.menuName,
to: '/'+elements.menuName.toLowerCase(),
}]
return subnav
}
})
})
}
export function getNav() {
const [nav, setNav] = useState([]);
useEffect(() => {
axios.get('api/sql', {
params: {
table: 'main_menu'
}
})
.then(response => {
response.data.map((element) => {
if (element.isLink == '1' && element.parentID == null){
var type = 'CNavItem'
const icon = element.icon
const newnav = [{
component: navtype[type],
name: element.menuName,
to: '/'+element.menuName.toLowerCase(),
icon: <CIcon icon={icons[icon]} customClassName="nav-icon" />,
}]
setNav((prevNav) => prevNav.concat(newnav));
}
if (element.isGroup == '1' && element.parentID == null){
var type = 'CNavGroup'
const icon = element.icon
const newnav = [{
component: navtype[type],
name: element.menuName,
icon: <CIcon icon={icons[icon]} customClassName="nav-icon" />,
items: subNav(element.menuID)
}]
setNav((prevNav) => prevNav.concat(newnav));
}
if (element.isHeader == '1'){
var type = 'CNavTitle'
const newnav = [{
component: navtype[type],
name: element.menuName,
}]
setNav((prevNav) => prevNav.concat(newnav));
}
})
})
.catch(error => {
console.error(error);
});
}, []);
return nav
}
export default getNav