U
U
uuushka2015-12-07 12:25:39
JavaScript
uuushka, 2015-12-07 12:25:39

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();  
}

console.log('response', Store.fetchData()) writes
Promise {: "pending", : undefined}

In actions, store, source data is received, but I can't render it.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
Nikita Gushchin, 2015-12-07
@iNikNik

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 }); //как пример

R
Roman_Kh, 2015-12-31
@Roman_Kh

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 question

Ask a Question

731 491 924 answers to any question