import Axios from "axios";
import { useEffect, useState } from "react";
function Transactions() {
const [allDetails, setAllDetails] = useState();
const userDetails = JSON.parse(localStorage.getItem('bankDetails'));
const transactons = JSON.parse(userDetails[0].transactions);
useEffect(() => {
Axios.get('http://localhost:3001/transactTo')
.then((res)=>{
setAllDetails(res.data);
})
}, []);
return (
<div className="parent">
<div className="account">
<h1>Transactions</h1>
{transactons.map((value, key1)=>{
return(
<div key={key1} className="transaction">
<div>
{allDetails.map((user, key2)=>{
user.acc_no = parseInt(user.acc_no);
if(user.acc_no === value.to){
return <div key={key2}style={{'background':`url(/${user.image}.png)`}} className="userdp"></div>;
}
})}
{value.amount}||
{value.to || value.from}
</div>
</div>
);
})}
</div>
</div>
);
}
export default Transactions;
I'm trying to map an array inside a mapped array and the thing is the second map shows an error TypeError: Cannot read properties of undefined (reading 'map')
. As soon as I comment the second map of 6 lines and run the code, it runs and again if I remove the comments it again runs properly but doesn't runs in the first render.
Can anyone give a proper solution. I tried Array.map inside Array.map is not working but it didn't helped.
CodePudding user response:
The problem has nothing to do with the map
being inside another map
.
allDetails
is undefined
when the component is first rendered. Since undefined
is not an array, you cannot call map
on it.
You need to check for allDetails
to be loaded, for example like so:
function Transactions() {
const [allDetails, setAllDetails] = useState();
const userDetails = JSON.parse(localStorage.getItem('bankDetails'));
const transactons = JSON.parse(userDetails[0].transactions);
useEffect(() => {
Axios.get('http://localhost:3001/transactTo')
.then((res)=>{
setAllDetails(res.data);
})
}, []);
return (
<div className="parent">
<div className="account">
<h1>Transactions</h1>
{transactons.map((value, key1)=>{
return(
<div key={key1} className="transaction">
<div>
{allDetails && allDetails.map((user, key2)=>{
user.acc_no = parseInt(user.acc_no);
if(user.acc_no === value.to){
return <div key={key2}style={{'background':`url(/${user.image}.png)`}} className="userdp"></div>;
}
})}
{value.amount}||
{value.to || value.from}
</div>
</div>
);
})}
</div>
</div>
);
}
export default Transactions;
CodePudding user response:
I guess here you missed []
inside useState
. As allDetails
is an array, we should assign it like array in hooks.
Try with
const [allDetails, setAllDetails] = useState([]);