Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React js map() undefined is not a function

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.

like image 622
this_is_ender Avatar asked Feb 11 '15 20:02

this_is_ender


Video Answer


2 Answers

Change your getInitialState(). Currently your data is an object literal and object literals doesn't support map(). Change it to an array.

like image 149
Henrik Andersson Avatar answered Sep 22 '22 08:09

Henrik Andersson


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

like image 32
Adil Avatar answered Sep 22 '22 08:09

Adil