I am working on a mern project. and I want to render an array of objects in my react page through my database by using useState.
my code
import React,{useEffect,useState} from 'react'
import { NavLink,useParams } from 'react-router-dom'
import Adminbar from './Adminbar'
const Contracter = () => {
const { id } = useParams();
const [member,setMember] = useState([])
const tofetchallmember = async ()=>{
try {
const res = await fetch(`/member/${id}`,{
method :"GET",
headers : {
Accept : "application/json",
"Content-Type" : "application/json"
},
credentials : "include"
})
const data = await res.json()
setMember(data)
console.log(data.name);
console.log(data.projectmembers[0]);
console.log(data.projectmembers[0].attendance);
} catch (error) {
console.log(error);
}
}
useEffect(() => {
tofetchallmember()
}, [])
return (
<>
<Adminbar/>
<div className='container mt-5'>
<div className='row'>
<div className='col-sm-5 col-md-5 col-lg-5'>
<div class="row align-items-md-stretch">
<div class="h-100 p-5 text-bg-light rounded-3">
<h2>Contracter List of {member.name}</h2>
<ol class="list-group list-group-numbered mt-5
To achieve this I tried the above code. If I tried this:
setMember(data)
console.log(data.name);
console.log(data.projectmembers[0]);
console.log(data.projectmembers[0].attendance);
it perfectly shows all the data in my console but when I tried to render it in my html code through this:
<h2>Contracter List of {member.projectmembers[0].name}</h2>
it shows the following error:
Uncaught TypeError: Cannot read properties of undefined (reading '0')

projectmembersas an array before the async call has returned and created the array. Simplest fix is to check whether the array exists before trying to access it; when the data returns the component will re-render and should display correctly.[]?<h2>Contracter List of {member?.projectmembers[0]?.name}</h2>projectmembersis my backend data. i got all my data inmemberinconst [member,setMember] = useState([])... how to check that array. ?