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?
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.