React / Flux is the best way to track api and update updates on new data?

I am trying to figure out how to update the store when the api returns changed data. One of my components is supposed to display "live" data when other users write data to the api. What's the best approach? Polling asynchronous data on an interval?

I am using ReactJS / AltJS and I am currently using jQuery to make async api calls in my activities.

Thank!

BookActions.js:

getBook(bookId) {
  $.ajax({ url: '/api/books/' + bookId })
    .done((data) => {
      this.actions.getBookSuccess(data);
    })
    .fail((jqXhr) => {
      this.actions.getBookFail(jqXhr);
    });
}

      

BookStore.js

import alt from '../alt';
import BookActions from '../actions/BookActions';

class BookStore {
  constructor() {
    this.bindActions(BookActions);
    this.books = [];
  }

  onGetBookSuccess(data) {
    this.books = data;
  }

  onGetBookFail(errorMessage) {
    toastr.error(errorMessage);
  }

}

export default alt.createStore(BookStore);

      

+3


source to share


1 answer


First of all, you have to determine what "live" data is. After the user writes some data to the server, how long can you wait until you know the new data? If you want to be notified within 1 second, you also need to carefully design your backend system.

In your question, I am assuming a few seconds delay is acceptable. One of the simpler solutions is a survey. As per edit the document , you can create a timer in componentDidMount

to periodically call the API and clear everything in componentWillUnmount

.



Don't put timer logic in actions that can be used by human components.

+2


source







All Articles