8

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.

7
  • Additionally to the provided answer: you normally don't perform ajax requests from a component. Commented Feb 11, 2015 at 20:29
  • @zerkms Disagree, normally you would if you're not using Flux. Commented Feb 11, 2015 at 20:29
  • @limelights even if you're not following Flux - you need to use some other architectural design pattern that separates presentation from persistence and business logic. Commented Feb 11, 2015 at 20:31
  • @zerkms No, I still disagree. I've made widgets that need to be self contained using React. There it makes sense to do this. Commented Feb 11, 2015 at 20:32
  • @limelights being self-contained does not mean that everything should be placed in a single object. Every object should be responsible for one small aspect. Don't you agree the provided code is hard to test? Commented Feb 11, 2015 at 20:33

2 Answers 2

15

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

Sign up to request clarification or add additional context in comments.

1 Comment

Wow... that was a simple fix. Thanks!
3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.