I am learning react through creating some sample projects using Meteor. I think I am getting a grasp of it but now I am stuck again.
I am using a twitter API to fetch the most recent 3 tweets from the BOINGBOING twitter page. I can confirm that I have the API working and can console out an array of objects containing created_at
, text
, & value.entities.media[0].media_url
which is basically the image url of a tweet.
What I am trying to achieve is to display the three tweets within a div
tag containing an img
& 2 p
tags.
I am forming the DOM with JSX, pushing the DOM for current tweet into an array and then passing this array to render(). I thinking an array of React elements should render right? So what is my mistake, I am seeing nothing?
getTweets: function(){
Meteor.call('fetchTweets', function(error, result){
var res = [];
// cycle through the results and build reat elements
_.each(result, function(value, key, list){
var {created_at, text, ...other} = value;
if (value.entities.media != undefined) {
// no image
let node = (
<div>
<p>{created_at}</p>
<p>{text}</p>
</div>
);
console.log(node);
res.push(node);
} else {
// has image
let node = (
<div>
<img src={value.entities.media[0].media_url} alt=""/>
<p>{created_at}</p>
<p>{text}</p>
</div>
);
res.push(node);
}
})
console.log(res);
return res;
});
},
render: function() {
return (
<div>
<div className="alltweets">{this.getTweets()}</div>
</div>
);
}
2
Answers
I don’t know meteor, but it looks like
Meteor.call
is asynchronous, so it can’t just returnres
. You’d probably need to callsetState({ someKey: res })
in your asyncCallback , and use that state in yourrender()
call.I’m not sure you’re using react correctly in this situation, here’s how I’d do it.
And then you would render that to the DOM.