0

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.

The structure of database is Database structure

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')

4
  • Your component is trying to access projectmembers as 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. Commented Jan 20, 2023 at 14:02
  • Have you tried using the optional chaining (?.) operator to check the first render when the value is []? <h2>Contracter List of {member?.projectmembers[0]?.name}</h2> Commented Jan 20, 2023 at 14:02
  • @DanielBeck projectmembers is my backend data. i got all my data in member in const [member,setMember] = useState([])... how to check that array. ? Commented Jan 20, 2023 at 14:09
  • asynchronous code is asynchronous. The data hasn't reached the front end by the time you first try to access it. The optional chaining operator suggested above is one way to handle this. Commented Jan 20, 2023 at 14:12

2 Answers 2

1

The problem is caused because in the first render your state member is an empty array, so when it tries to access projectmembers[0].name it crashes. You should use optional chaining (?.) operator to solve with your actual code <h2>Contracter List of {member?.projectmembers[0]?.name}</h2> or check if the array exists:

const Contracter = () => {
  //all the previous code
  return (
   {member.length===0 ? <p>No data</p> : member?.projectmembers[0]?.name}
  )
}
Sign up to request clarification or add additional context in comments.

Comments

1

Initially, when the component is loaded, the member state is an empty array []. So you will not have any data in the state, you cannot access member.projectmembers

Put a validation to check if the member object has projectmembers or not as below.

 { member.projectmembers && member.projectmembers.length > 0 ? <h2>Contracter List of {member.projectmembers[0].name}</h2> : null}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.