Edgesoft
Edgesoft

Reputation: 282

react js fetching data from server and render

I'm using React js and the Biff Flux implementation. I have a question on the best way of achieving load from server.

getInitialState: function(){
    return{
      loading: true
    };
},
componentDidMount: function(){
  MyAction.fetchsomeData();
},

storeDidChange: function(){
  var data = MyStore.getsomeData();
  // set state
  this.setState({loading: false});
},
render: function(){
  // wait for render until response from server
  // really?
  if( this.state.loading ){
     return null;
  }
  // do render
}

Is this the correct way of doing it? Sometimes I have a Controller that loads the data and sends it as props to it's child components but still I don't know the best way of render the component when I must wait for a response from the server.

Upvotes: 0

Views: 1357

Answers (1)

divyenduz
divyenduz

Reputation: 2027

Usually you would want to have the ajax call at the top component. And you would like to send data to child components via props.

While your methods looks correct. You can use localStorage to cache the response for the 1st time and show it until original data is fetched from the server.

This will make your app look faster.

Something like:

getInitialState: function(){
    // try to return stale state from cache
    // if not available, set loading to true
},
componentDidMount: function(){
  MyAction.fetchsomeData();
},

storeDidChange: function(){
  var data = MyStore.getsomeData();
  // set state and set local storage cache
  this.setState({loading: false});
},
render: function(){
  // wait only if local storage does not have cached stale state
  if( this.state.loading ){
     return null;
  }
  // do render
}

If you are not looking at a cache solution, then your method is fine. I hope this helps you.

Upvotes: 1

Related Questions