Reputation: 494
The goal is to pull in the nested array "records". My current output displays the array within the react console, but with an error. I will try and be as concise as possible but will keep things short.
The error screen has 3 lines that are referencing _getRecords so im positive that _getRecords is the problem child.
class RecordBox extends Component {
constructor() {
super();
this.state = {
showComments: false,
results: []
};
}
render(){
const records = this._getRecords();
return (
// jsx template code...
);
}
// API Call
_fetchRecords() {
$.ajax({
method: 'GET',
url: 'http://apidata:8888/data.json',
success: (results) => {
this.setState({ results });
},
error: () => {
console.log('error');
}
});
}
_getRecords() {
// TypeError: this.state.results.map is not a function...
return this.state.results.map((record) => {
return <Comment body={record["Contractor Name"]} />
});
}
}
I have a feed that looks like the below. I do not have permission to modify this.
{
"result": {
"records": [
{
"id": 1,
"email": "[email protected]",
"author": "Clu",
"Contractor Name": "Just say no to love!!",
"avatarUrl": "https://placeimg.com/200/240/any"
},{
"id": 2,
"email": "[email protected]",
"author": "Anne Droid",
"Contractor Name": "I wanna know what love is...",
"avatarUrl": "https://placeimg.com/200/240/any"
}
]
}
}
Upvotes: 1
Views: 1379
Reputation: 89
I think you just aren't setting the state to the right thing. Your state.results is currently an object. Just make sure when you set your state, you set state.results to results.result.records
this.setState({ results: results.result.records })
One thing you could also do is map the results directly in the jsx code and skip using the _getRecords function.
<div>
{
this.state.results.map( ( record ) => {
return <Comment />
}
}
</div>
This is the way I usually write this as it's easier for me to read, but it's personal preference.
I hope this helps!
Upvotes: 1
Reputation: 1602
The _fetchRecords function needs to change to:-
_fetchRecords() {
$.ajax({
method: 'GET',
url: 'http://apidata:8888/data.json',
success: (results) => {
this.setState({ results: results.result.records });
},
error: () => {
console.log('error');
}
});
}
Upvotes: 0