I have an object that I'm filling with some information, when logging the object it shows empty but when opening the object up in chrome, it shows that correct details are filled.
This is what the logs look like
closed: closed obj
open: opened obj
When mapping the object I get the following error Cannot read properties of undefined (reading 'map')
Am I doing something wrong?
here is my code:
function Admin() {
const [loading, setLoading] = useState<boolean>(false);
const [webAppTypes, setWebAppTypes] = useState<IWebAppType[]>([]);
var nm: { [key: number]: Array<IWebApp> } = {};
useEffect(() => {
setLoading(true);
fetch(`${process.env.REACT_APP_API_URL}/webapptype/read_all`, {
headers: headers,
})
.then((data) => {
setLoading(false);
return data.json();
})
.then((res) => {
setWebAppTypes(res);
});
}, []);
useEffect(() => {
webAppTypes.map((a) => {
fetch(`${process.env.REACT_APP_API_URL}/webapp/read_all/${a.id}`, {
headers: headers,
})
.then((data) => {
return data.json();
})
.then((data) => {
let arr: Array<IWebApp> = [];
data.map((a: any) => {
const model: IWebApp = {
id: a.id,
name: a.name,
description: a.description,
link: a.link,
image: a.image,
};
arr.push(model);
});
nm[a.id] = arr;
});
});
console.log(nm);
}, [webAppTypes]);
if (loading) return <h6>Loading...</h6>;
return (
<div style={{ padding: 100, paddingLeft: 200, width: 500 }}>
{webAppTypes.map((a) => {
return (
<Accordion key={a.id}>
<AccordionSummary
expandIcon={<ExpandMoreIcon />}
aria-controls="panel1a-content"
id="panel1a-header"
>
<Typography>{a.name}</Typography>
</AccordionSummary>
<AccordionDetails>
<>
{nm[a.id].map((t) => {
return <Typography>{t.id}</Typography>;
})}
</>
</AccordionDetails>
</Accordion>
);
})}
</div>
);
}
Any help would be appreciated.
@new_ting it appears you are returning the data as json and trying to map from there. You need to parse the json before mapping it, mapping it as json won't work.
return data.json(); //this is the json I was talking about
})
.then((data) => {
let arr: Array<IWebApp> = [];
data.map((a: any) => {//here is the mapping being done to the json string