Reputation: 649
I want to render items from props, I can do it with initial state, but not with response from server. My render function :
const { data } = this.props;
return (
<div >
{data.map((item, index) =>
<div key={index} className="row">
<span data = { data } className="number col-4 col-md-8">{item._id}</span>
<span data = { data } className="date col-4 col-md-2">{item.date}</span>
<span data = { data } className="tag col-4 col-md-2">{item.tag}</span>
<div className="col-md-12 ">
{item.text}
</div>
</div>
)}
</div>
)
}
I get this mistake :
TypeError: e.map is not a function
response : Object {data: Array(12), status: 200, statusText: "OK", headers: Object, config: Object…}
Upvotes: 5
Views: 19899
Reputation:
Just add these words to your map function, Because you need check if the array was existed then execute map function
const { data } = this.props;
return (
<div >
{data && data.length && data.map((item, index) =>
<div key={index} className="row">
<span data = { data } className="number col-4 col-md-8">{item._id}</span>
<span data = { data } className="date col-4 col-md-2">{item.date}</span>
<span data = { data } className="tag col-4 col-md-2">{item.tag}</span>
<div className="col-md-12 ">
{item.text}
</div>
</div>
)}
</div>
)
}
Upvotes: 1
Reputation: 649
Had to change parent component change this:
this.setState({
data: response
})
to
this.setState({
data: response.data
})
I've tried to reach the data from the child component, but it din't work (probably because of the map function)
Upvotes: 3
Reputation: 24
You can use default value of data
, when response is pending. In this time data
is not defined
const { data = [] } = this.props;
Or use condition in jsx:
render() {
if (!data || !data.length) return null;
...
}
Upvotes: 0
Reputation: 2307
It looks like your response is just the raw response. If you're using fetch, this is what the promise chain should look like:
fetch(fromMySource).then(resp => resp.json()).then(data => doSomething(data));
It looks like you might be trying to use resp directly which would make your data array look like the response object you posted in your question.
Upvotes: 2