Reputation: 21
I'm trying to display a list of Items from an API with react.
In my component class Explore
I want to code the get and display data from the api.
While using .map
on items
, this.state
, items.state
or items.state.results
(on the data I need from my query) I'm getting the following errors:
Cannot read property 'map' of undefined** || **TypeError: this.state.map is not a function
Unhandled Rejection (TypeError): items.map is not a function
Is the problem in the structure of the component itself? With render or the declaration of items?
Did I miss something with this
or this.state
? Do I need to add a function to the .map
(or change the key)?
When I console log (in the render part of the code) items
or items.results
I do get the data i need before the map call.
Thank you for your help.
import React, { Component} from 'react';
import './App.css';
import ItemDetail from './ItemDetail';
class Explore extends Component {
constructor(props){
super(props);
this.state = {
items: [],
};
}
componentDidMount(){
fetch('https://myapi/search/photos?query=myquery&client_id=myclientid')
.then(res => res.json())
.then(json => {
this.setState({
isLoaded: true,
items: json,
});
});
}
render() {
var { items } = this.state;
return (
<div>
<h1>Nav to</h1>
<div>
<ul>
{items.map(item => (
<li key={item.results.id}>
<a href={ItemDetail}>Alt: {item.results.altdescription} | </a>
Desc:{item.results.desc}
</li>))}
</ul>
</div>
</div>
);
}
}
export default Explore;
Upvotes: 1
Views: 10888
Reputation: 1
Inside the render method, you have defined a state as an object var { items } = this. state; so the map will not work. In order to make the map work define state as var [ items ] = this.state;
Upvotes: 0
Reputation: 211
Try adding a check to see if items is set and if its an array before calling .map on it.
On the line where you call map add items && !!items.length && items.map...
Also the issue could be in the format in which you are receiving data.
Try to console.log
the json
before calling this.setState
Upvotes: 4