Home > OS >  How to render array of objects in Reactjs using useState?
How to render array of objects in Reactjs using useState?

Time:01-20

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 >

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

CodePudding user response:

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

CodePudding user response:

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}

  • Related