I am new to React and I am going a little crazy trying to figure out what I am doing wrong. I am trying to iterate through a json array that I get from an ajax call. When I mock the data it works perfectly, but when I make an ajax call to get the exact same data it gives me undefined is not a function (evaluating 'this.state.list.map()')
the array:
[ { "name": "drop1" }, { "name": "drop2" }, { "name": "drop3" } ]
the function:
var List = React.createClass({
getInitialState: function() {
return {data: {}};
},
componentDidMount: function() {
$.ajax({
url: ACTUAL_URL,
dataType: 'json',
success: function(data){
this.setState({data: data});
}.bind(this),
error: function(xhr, status, err){
console.error(url, status, err.toString());
}.bind(this)
});
},
render: function() {
return (
<ul className="droplist">
{this.state.data.map(function(l){
return (<li>{l.name}</li>)
})}
</ul>
);
}
});
Any help is much appreciated.
Change your getInitialState()
.
Currently your data is an object literal and object literals doesn't support map()
.
Change it to an array.
In my case I was trying to use array.map but my data actually was an object rather than array so using Object.keys(data)
is the right way to iterate over objects:
Object.keys(data).forEach(item => {...});
// OR
Object.keys(data).map(item => {...});
Read details here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With