I am new to react and have been debugging this from yesterday and I finally decide to post as I am clueless of what is happening.
The following react code fetches data from the api and then renders it on the UI. But, there are few strange things happening here.
I get error saying as TypeError: Cannot read property 'map' of undefined
initially but when I comment out {renderTableData(data)}
& save and then again uncomment & save, the data is rendering perfectly on the UI
I am thinking that before even the data gets fetched from API, it is getting passed to the function renderTableData
which is why in the console undefined
is printed.
Here is the code
export default function TenantList(){
const [data, setData] = useState([]);
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/users').then((response)=>{
return response.json();
}).then((data)=>{
setData(data)
})
},[]);
function renderTableData(data) {
console.log("hello ", data)
return data.map((student, index) => {
const { name, email } = student //destructuring
return (
<tr key={name}>
<td>{name}</td>
<td>{email}</td>
</tr>
)
})
}
return (
<>
<div>
{renderTableData(data)}
</div>
</>
)
}
Please suggest a workaround
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…