2

I am facing a very similar problem to this question, but I am fetching data using a Promise and want to render it into the DOM when it comes through. The console.log() displays all the items correctly. I think my problem is that the lodash.map returns an array of <li> elements, and so I am trying to call this.renderItems() in order to render (but renderItems() doesn't seem to exist). Am I doing something unconventional, is there an easier way, is there an equivalent function to replace my renderItems()?

   renderArticleHeadline: function(article) {
      console.log('renderArticleHeadline', article.headline);
      return (
         <li>
            {article.headline}
         </li>
      )
   },
   render: function() {
      return (
         <div>
            <ul>
               {
                  this.renderItems(
                     this.fetchFrontPageArticles().then(data => {
                        lodash.map(data, this.renderArticleHeadline)
                     })
                  )
               }
            </ul>
         </div>
      );
   }
3
  • 2
    Remember that render is called synchronously, yet your fetch is async. So, the render function has already completed by the time your data has returned. So, nothing will show. Commented Apr 4, 2015 at 12:48
  • 1
    IIRC render should not call fetch, the control flow should be in the reverse direction. Commented Apr 4, 2015 at 12:53
  • 1
    @Bergi it's not so much an IIRC (React is just a view library) as common sense :) That said the issue here is probably that renderItems is fed a promise. Commented Apr 4, 2015 at 13:59

1 Answer 1

8

It should be something like this

getInitialState: function() {
    return {
        items: []
    };
},
renderArticleHeadline: function(article) {
    return (
         <li>
            {article.headline}
         </li>
    );
},
componentDidMount: function() {
    this.fetchFrontPageArticles().then(data => {
        this.setState({
            items: data
        });
    });
},
render: function() {
  var items = lodash.map(this.state.items, this.renderArticleHeadline);
  return (
     <div>
        <ul>
            {items}
        </ul>
     </div>
  );
}

P.S. read thinking in react

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

2 Comments

Yes this looks much more like it with fetchFrontPageArticles calling setState
FWIW newer React versions will probably complain if you don't have a key on the renderArticleHeadline <li> elements OR more properly move the <li> elements to another React class so that it can manage it as fragments.

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.