React Map stopped working

React Map stopped working
0

#1

Here is the code:
var ShowTop = React.createClass({ render: function(){ var listBoard = recentData.map(function(data){ return ( <tr> <th> {data.position} </th> <th> <a href={data.userLink} target="_blank">{data.username}</a> </th> <th> {data.recent} </th> <th> {data.alltime} </th></tr> ); }); return( <table> <tr> <th>#</th> <th>Camper Name</th> <th>Recent Points</th> <th>All Time Points</th> </tr> {listBoard} </table> ) } });

This code was working, I don’t think I changed anything and then suddenly it stopped working…
I think it may be an issue with the listBoard variable, becuase when I remove it everything works smoothly.

here is the codepen link for the full code, thanks: http://codepen.io/roman_fedoruk/pen/dNPdaP?editors=0011


#2

It seems like it’s trying to map over something that doesn’t exist when the component is rendered, it might be because of the API call.

A workaround could be in your render method add

if (!this.recentData) {

  return ("Loading...");

}

return (
... Your normal component
)

#3

You have no guarantee that by the time your component renders on the page, the AJAX request would have returned the data. That’s why it might sometimes work, but other times the request might take longer to complete.

A common pattern for such situation in React seem to be to move your getData function into the componentWillMount method and once the data is retrieved, assign it to state, so the component will re-render and then you can do something like what @Oxyrus mentioned above


#4

Ok, thanks! so should I put the listBoard variable into componentWillMount()?


#5

What do you mean by my normal component?


#6

What you have in your render method currently.


#7

I’m sorry but I don’t seem to understand where to put the code, could you point me to where exactly I should put it?


#8

You put it in replace of the ... Your normal component in your render method.