3

I'm creating simple application in reactjs/flux way. I have MessageStore and UserStore that contain this data:

MessageStore contains

[
    {"id": 1, "text": "It is a test message", "userId": 155123}
]

UserStore contains

[
    {"id": 155123, "name": "Thomas Brown", "age": 35}
]

I'm creating component to display message. It needs user name, but it only has userId obtained from props.

Currently I use the initial-ajax-like approach to get this data (warn: es6 react syntax):

componentDidMount() {
    var author = UserStore.getById(this.props.userId);
    this.setState({
        author: author
    })
}
render() {
    return (<a>{this.state.author.name</a>);
}

Is it correct? I figured out that in this case render function is called twice. Is there any other approach to do this? Rendering loading icon? Avoid rendering before data is retrieved?

3
  • 1
    Is what correct? render will be called once during the initial pass and then again when you update the state. If you don't like that pattern, you'd need to preload the data before creating your component. Commented Apr 6, 2015 at 12:40
  • @WiredPrairie does before also includes getIntitialState call? Commented Apr 6, 2015 at 12:56
  • I'm suggesting you could not create your component in whatever container normally hosts the component. Commented Apr 6, 2015 at 13:48

1 Answer 1

3

One should move the

var author = UserStore.getById(this.props.userId);
return({
    author: author
})

part to getInitialState LifeCycle.

getInitialState is called exactly once for each instance of the component, here you get a chance to initialize the custom state of the instance. Unlike getDefaultProps this method is called once each time an instance is created. At this point you have access to this.props.

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

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.