Click here to Skip to main content
15,867,975 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am having trouble iterating through my multi-deminsional array when I use the map function in reactjs. For some reason, when I ran the code for the first time it seem to be working. Then I reloaded the component and it never worked again. If someone could tell me what I am doing wrong, I would apperciate it very much.

I am getting this error when I run my code: TypeError: "linkArray[0] is undefined".

my code is below,

import React, {useEffect, useState} from 'react';
//import PropsTest from './propsTest';
  

const PaginationTest = (props)=>{
    const [linkArray, setLinkArray] = useState([]);

    

   useEffect(()=>{
    var formattedLinksArray = [];

    const link1 = [
        {id:0,url:"http://www.zero.com",item_name:"zero"},
        {id:1,url:"http://www.one.com",item_name:"one"},
        {id:2,url:"http://www.two.com",item_name:"two"},
        {id:3,url:"http://www.three.com",item_name:"three"},
        {id:4,url:"http://www.four.com",item_name:"four"}
    ];

    formattedLinksArray[0] = link1;

    const link2 = [
        {id:5,url:"http://www.five.com",item_name:"five"},
        {id:6,url:"http://www.six.com",item_name:"six"},
        {id:7,url:"http://www.seven.com",item_name:"seven"},
        {id:8,url:"http://www.eight.com",item_name:"eight"},
        {id:9,url:"http://www.nine.com",item_name:"nine"}
    ];

    formattedLinksArray[1] = link2;

    setLinkArray(formattedLinksArray);
    
},[]);

console.log(linkArray[0]);

   return (
       <div>
           <h1>Hello From Pagination Test</h1>
           {linkArray[0].map((link,index)=>
           
              <p key={index}>{link.url}</p>
           
           )}
        </div>
   )
}

export default PaginationTest;


What I have tried:

I tried initilizing the array outsidethe useEffect function but it did not work,
Posted
Updated 11-Jul-21 16:02pm
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900