I have array data in console how can i display it in react js?

6

I'm getting data from and API and its working fine in console but unable to display data in my frontend table.

Displaying below error:-

TypeError: Cannot read property 'map' of undefined

Now I'm getting array in console as given below:- enter image description here

My code:-

import React,{component, Component} from 'react';

class List extends Component{

    constructor(props){
        super(props);
        this.state = {
            items: [],
            isLoaded: false,
        }
    }

    componentDidMount(){

        fetch('url')
            .then(res => res.json())
            .then(data  => {
                console.log(data)
                this.setState({
                    isLoaded: true,
                    items: data
                })
                // console.log(json) 
            });
    }

    render(){

        var { isLoaded, items} = this.state;

        if(!isLoaded){
            return <div>Loading...</div>
        }
        else{
        return(
            <div className="List">

            <ul>
            {items[0].map(item =>(
         <li key={item.UserId}>
             {item.repos_url}
        </li>
        ))}
            </ul>

                </div>
        )
            
    }

}
}

export default List;

Answer will be appreciated!

answered question

3 Answers

8

It looks like data has the following shape:

data = {
  Table: [{
    UserId: 123,
    repos_url: 'foo',
  }, {
    UserId: 456,
    repos_url: 'bar',
  }, ...],
};

So one option would be to replace items[0].map(...) with items.Table.map(...).

Alternatively, replace:

this.setState({
  isLoaded: true,
  items: data,
});

With:

this.setState({
  isLoaded: true,
  items: data.Table,
});

And then also items[0].map(...) with just items.map(...).

posted this
5

You are referencing a wrong property. Try to map over Table array that is inside "items" state variable


     <ul>
         {items.Table.map(item =>(
             <li key={item.UserId}>
                 {item.repos_url}
            </li>
            ))}
     </ul>

posted this
2

You are using items[0].map(), you need to reference the table element in your items object by doing items.Table.map()

posted this

Have an answer?

JD

Please login first before posting an answer.