2

I'm rendering a react component that needs data that returns asynchronously. How should I pass this to the react component when it returns from the callback?

currently in render function:

var dataToReturn; 
asynchCall(args, function(err, results) {
  dataToReturn = results;
})

return (
    <MyComponent data={dataToReturn} />
)

This of course is not working out because the data has not returned yet. If I move the render into the callback, that seems like a bad programming pattern. Is there anything in the React API meant for this use case?

thank you!

2 Answers 2

3

Yes, like @Fouad said:

var NewComponent = React.createClass({ 
    componentDidMount: function() {
       asynchCall(args, function(err, results) {
          this.setState({data: results});
       }.bind(this));
    },

    return (
        <MyComponent data={this.state.data} />
    )
});

Also, check out documentation page Load Initial Data via AJAX

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

2 Comments

But to be clear, do this in componentDidMount, and bind the callback so this.setState doesn't mean window.setState.
@FakeRainBrigand yeah, you are right, thank you. I have corrected my answer.
2

Instead of local variables you should use this.state & this.setState which will trigger a re-render. Check out this link on fetching from the server http://facebook.github.io/react/docs/tutorial.html#fetching-from-the-server

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.