Answer the question
In order to leave comments, you need to log in
React and Flux: how to get data on page load?
Stupid question, but I can't find a solution...
When I go to another page, I need to get data from the server (for example, first and last name) and display it on the page.
So, when loading componentDidNount pulls the action:
componentDidMount() {
Store.fetchData();
}
Promise {: "pending", : undefined}
Answer the question
In order to leave comments, you need to log in
Store.fetchData() returns a Promise. You need to wait until the response comes and then render your component.
Or subscribe to the Store in some way (depends on the chosen implementation of flux)
Store.on('DATA_LOADED', (data) => this.setState({ data }); //как пример
In theory, your component has no idea whether or not to download data from the server. Only store knows about it . Therefore, the component should only request data from the store , but at the same time be able to understand that it was the data that was received in response and then draw the usual content, or that the information was received in response that the data is being loaded from the server and then draw other content (for example, with icon and download message).
More or less like this:
class SomeComponent {
...
componentDidMount() {
Store.addListener("DATA_CHANGED", this.handleChanged)
Store.addListener("DATA_LOADED", this.handleLoaded)
}
...
handleLoaded(){
// just force rendering (you can do something smart beforehand though)
this.forceUpdate()
}
...
renderContent(){
// your usual render code
...
}
renderLoading(){
return <Icon type="spinner" spin />
}
render(){
if(Store.isLoading()){
return this.renderLoading()
} else {
return this.renderContent()
}
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question