How to set ajax data to stream?

I am working on my first FLUX app and stumbled upon this issue. I want to receive data from the server and pass it to my component.

Let's say I have a component method ...

loadMore() {
  AppActions.getCards();
}

      

... and storage:

$.ajax({
  url: '../data.json',
  dataType: "json",
  success: function (data) {
    // ???
  }.bind(this),
  error: function (xhr, status, err) {
    console.error(status, err.toString());
  }.bind(this)
});

      

not really sure how to get it right. inside ajax this

obviously undefined

also can't return a value from it, or can I?

sure it's trivial but would be very grateful for the advice

+3


source to share


2 answers


According to Facebook flux-chat example, you can do the following:

Trigger action from component

loadMore() {
    AppViewActionCreators.getCards();
}

      

AppWebAPIUtils method is called in AppViewActionCreators

getCards() {
    AppWebAPIUtils.getCards();
}

      

Make an ajax call to AppWebAPIUtils



getCards() {
    $.ajax({
        url: '../data.json',
        dataType: "json",
        success: function (data) {
            AppServerActionCreators.recieveCards(data);
        },
        error: function (xhr, status, err) {
            console.error(status, err.toString());
        }
    });
}

      

On successful launch of server action in ServerActionCreators, dispatching event with data

recieveCards(data) {
    AppDispatcher.dispatch({
        type: ActionTypes.RECIEVE_CARDS,
        data: data
    });
}

      

Retrieving data by saving and modifying a change event

AppStore.dispatchToken = AppDispatcher.register(function (action) {
    switch (action.type) {
        case ActionTypes.RECIEVE_CARDS:
            _cards = action.data.cards;
            AppStore.emitChange();

            break;
    }
});

      

You must have view creators and server actions to prevent circular dependency.

+3


source


Do this in your action handler. So the stream will be:

  • Component call actions
  • The action handler will fetch data
  • As soon as the data arrives, the action will dispatch an event notifying about the data
  • Stores listening to the event will receive data
  • Stores will emit a change event
  • Components that depend on this store will update


In your action handler, you can dispatch an event to which you start loading data so that you can update the store state and UI.

Fluxible explains it very clearly: http://fluxible.io/api/actions.html

+1


source







All Articles