Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preload data in reactjs component

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?

like image 979
ivstas Avatar asked Sep 27 '26 21:09

ivstas


1 Answers

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.

like image 97
IcyBright Avatar answered Sep 29 '26 10:09

IcyBright



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!