flux icon indicating copy to clipboard operation
flux copied to clipboard

Store change listener fired before dispatcher's finished dispatching.

Open wayneashleyberry opened this issue 11 years ago • 29 comments

This is seemingly related to all of those "Cannot dispatch in the middle of a dispatch" issues, but I've narrowed it down to a store listener being triggered before the dispatcher's finished up.

Should that ever happen?

I can use the setTimeout hack, or the queue suggested in #106 but it doesn't feel right.

In my setup I have a login component with the following listener:

  onAuthStoreChange: function() {
    if (AuthStore.userIsAuthenticated() === true) {
      this.transitionTo('people');
    }
  },

Now when that gets fired I kind of expect the dispatcher to be finished dispatching... but it's not. So then when I transition to a new route and new actions are created there are obviously problems...

Is there any way to get listeners to only be triggered once the dispatcher's done?

Just to be clear, all of my actions are being created in the same place (with action creators) and this isn't a case of actions creating actions etc.

wayneashleyberry avatar Jan 28 '15 15:01 wayneashleyberry

p.s. Hope everyone's having fun at the conf :)

wayneashleyberry avatar Jan 29 '15 07:01 wayneashleyberry

I think this is expected. The stores' dispatcher-registered listeners are called sequentially on a trampoline of sorts, so the #dispatch() function call isn't popped off the stack until all of the stores's callbacks have returned, then #dispatch() returns. Your store is likely firing it's 'change' event in the same execution context, so onAuthStoreChange is called while the function call to #dispatch() is still sitting on the stack waiting to return.

Afaik, the only thing you're guaranteed is that any required browser repaint won't happen until after the call to #dispatch() returns, and that that browser repaint will include all updates to reflect the singular point in time/state that exists after the last dispatch.

sterpe avatar Jan 30 '15 19:01 sterpe

I don't think we are going to change Dispatcher to provide a hook after the dispatch completes, but internally we are looking very seriously at updating Dispatcher to provide a hook after all data mutations and just before _stopDispatching is called. That is, just before this line: https://github.com/facebook/flux/blob/master/src/Dispatcher.js#L195 That change will make it to GitHub if we find that it helps us internally at FB with our applications.

fisherwebdev avatar Feb 04 '15 07:02 fisherwebdev

I encounter similar error. Error: Invariant Violation: Dispatch.dispatch(...): Cannot dispatch in the middle of a dispatch

I got this error when I tried to start another dispatch in a listener that is triggered by emitChange() of a Store. I can workaround this by below two approaches, but both look like a hack

  1. Invoke listener method by setTimeout

  2. Make the emit async (using setTimeout as well)

    emitChange: function() {
      var self = this;
      window.setTimeout(function() {
        self.emit(CHANGE_EVENT);
      }, 1)
    },
    

So my question is that when a dispatch should be treated as done/completed, after the executions of all listeners on a `Store', or not care the execution of the listener (in which case I think we should make the emit async)

fantasy8-me avatar Apr 01 '15 09:04 fantasy8-me

^^^ That's a hack that should be avoided. Dispatch-within-a-dispatch errors are caused by improper code design 99.9% of the time. Instead of doing the setTimeout, do what you need to do in response to the original action. I think this is most often a reflection of equating actions with setters -- they are not the same.

fisherwebdev avatar Apr 02 '15 16:04 fisherwebdev

@fisherwebdev how do you guys feel about serial dispatches inside some Actioncreator.action()?

I.e:

dispatcher.dispatch({}); dispatcher.dispatch({});

Is this ok or better to merge into a single action type?

Sent from my iPhone

On Apr 2, 2015, at 9:40 AM, Bill Fisher [email protected] wrote:

^^^ That's a hack that should be avoided. Dispatch-within-a-dispatch errors are caused by improper code design 99.9% of the time. Instead of doing the setTimeout, do what you need to do in response to the original action. I think this is most often a reflection of equating actions with setters -- they are not the same.

— Reply to this email directly or view it on GitHub.

sterpe avatar Apr 02 '15 20:04 sterpe

@sterpe that's an interesting question. Do you have a real example?

I guess you should fire only one action which describes in whole what happened and stores should react to that single change.

I want to know what @fisherwebdev has to say anyway.

luisherranz avatar Apr 03 '15 10:04 luisherranz

Say WebAPIUtils does something like

ContactsApiGetsResponse.then( f(x) { // inform spinner status store or whatever emit change dispatcher.dispatch ({ actiontype: "response-succes" data:null }) //store should load this new data and emit change dispatcher.dispatch({ actiontype: "load-API-data-into - relevant store" data:x.responsedata })

Sent from my iPhone

On Apr 3, 2015, at 3:42 AM, Luis Herranz [email protected] wrote:

@sterpe that's an interesting question. Do you have a real example?

I guess you should fire only one action which describes in whole what happened and stores should react to that single change.

I want to know what @fisherwebdev has to say anyway.

— Reply to this email directly or view it on GitHub.

sterpe avatar Apr 03 '15 15:04 sterpe

In that case I think the store which is interested on that data should listen to the "response-success" event.

luisherranz avatar Apr 03 '15 15:04 luisherranz

Point being that the spinner store is really only a Boolean toggle and seems like it shouldn't need cases for every API actiontype just a generic request-started requested-ended : put up and pull down the spinner modal?

Sent from my iPhone

On Apr 3, 2015, at 8:33 AM, [email protected] wrote:

Say WebAPIUtils does something like

ContactsApiGetsResponse.then( f(x) { // inform spinner status store or whatever emit change dispatcher.dispatch ({ actiontype: "response-succes" data:null }) //store should load this new data and emit change dispatcher.dispatch({ actiontype: "load-API-data-into - relevant store" data:x.responsedata })

Sent from my iPhone

On Apr 3, 2015, at 3:42 AM, Luis Herranz [email protected] wrote:

@sterpe that's an interesting question. Do you have a real example?

I guess you should fire only one action which describes in whole what happened and stores should react to that single change.

I want to know what @fisherwebdev has to say anyway.

— Reply to this email directly or view it on GitHub.

sterpe avatar Apr 03 '15 15:04 sterpe

As @fisherwebdev has said above, you shouldn't confuse actions with setters.

Maybe you can do a regex of the actionType and check if it has "API" and "success" in it, or something like that.

luisherranz avatar Apr 03 '15 16:04 luisherranz

@LuisHerranz, In this case I don't feel like there's a confusion of setters and actions, though I can stand to be corrected. When my data store receives new items that is a server initiated action -- load these new items into the store and by extension dependent stores (through waitFor on same action) and component views respond to the emitted change. Otherwise it seems like you're proposing calling the store.loadItems method directly from say WebAPIUtils, skipping the dispatcher entirely, and then force emitting a change event so dependent views would rerender. I'm not sure how you see a store hierarchy working in that case?

In my particular case I must float a div at top of page on every CRUD action indicating that the changes were saved (or conversely not saved). This component (and it's store) doesn't particularly care about the details of any particular api request WebAPIUtils makes behalf of a particular data store that the user is manipulating. So not sure if it makes sense for this component to be aware of the unique actions that are relevant to unique stores when WebAPIUtils makes requests.

sterpe avatar Apr 03 '15 16:04 sterpe

@LuisHerranz, I don't know...I can't buy into regexing actionType strings, that seems potentially very brittle.

sterpe avatar Apr 03 '15 16:04 sterpe

What I mean by confusing setters and actions is that you shouldn't name your actions like this:

`actiontype: "load-API-data-into - relevant store"``

You should name them like

actiontype: "relevant-data-received"

and the relevant store, which is interested in that data, should be listening to that action.

luisherranz avatar Apr 03 '15 16:04 luisherranz

Perhaps, but that's a semantic issue in action naming--I feel like the heart is the question of what point you collapse actions together vs perform sequential dispatches, b/c say a certain component needs to respond to a multitude of different actions but in some sense doesn't need to be aware of them.

Sent from my iPhone

On Apr 3, 2015, at 9:55 AM, Luis Herranz [email protected] wrote:

What I mean by confusing setters and actions is that you shouldn't name your actions like this:

actiontype: "load-API-data-into - relevant store"`

You should name them like

actiontype: "relevant-data-received"

and the relevant store, which is interested in that data, should be listening to that action.

— Reply to this email directly or view it on GitHub.

sterpe avatar Apr 03 '15 17:04 sterpe

*component should be 'store'

Sent from my iPhone

On Apr 3, 2015, at 10:07 AM, [email protected] wrote:

Perhaps, but that's a semantic issue in action naming--I feel like the heart is the question of what point you collapse actions together vs perform sequential dispatches, b/c say a certain component needs to respond to a multitude of different actions but in some sense doesn't need to be aware of them.

Sent from my iPhone

On Apr 3, 2015, at 9:55 AM, Luis Herranz [email protected] wrote:

What I mean by confusing setters and actions is that you shouldn't name your actions like this:

actiontype: "load-API-data-into - relevant store"`

You should name them like

actiontype: "relevant-data-received"

and the relevant store, which is interested in that data, should be listening to that action.

— Reply to this email directly or view it on GitHub.

sterpe avatar Apr 03 '15 17:04 sterpe

@fisherwebdev There is another problem with firing emitChange in the middle of dispatch process: your app may receive inconsistent state from stores.

Consider simple example: Component depends on stores "A" & "B". Store "B" waitsFor store "A". When store "A" receives action and does "emitChange" store "B" hasn't done yet. Your component tries to update and recieves new state from store "A", but old state from store "B".

I faced with this issue with item / list stores, but pretty sure there might be other scenarios as well.

The only good way to solve this is to emitChange after all stores are done mutating. But there is no such option in Dispatcher yet. So what else can you do except setTimeout(emitChange, 0) at this point?

vladar avatar Apr 29 '15 16:04 vladar

@vladar There are a couple of different strategies to solving this problem. We believe we have a good solution and hope to open source it soon. But it's not the only solution.

Options:

  1. Debounce the change events in the React components. We currently think this is the best solution.
  2. Modify the dispatcher to call another set of callbacks at the end of the dispatch cycle. We went pretty far down this road, but in the end it did not seem as good as debouncing the change events. I think the primary concern was that it didn't seem like something the Dispatcher should be responsible for. It seemed like we were putting code in the Dispatcher that didn't really have anything to do with its original purpose, but was really tied to the store-view communication.
  3. Create an "OmegaStore" -- one that will waitFor all the other stores to update, and then emit change if those stores have changed. This solution seemed cool at first, but then wound up looking like a gigantic hack.

fisherwebdev avatar May 06 '15 08:05 fisherwebdev

Out of interest, is debouncing the change events in the components the solution you are open sourcing, or is there another solution on its way?

admmasters avatar May 08 '15 09:05 admmasters

You can use underscore, for example: http://underscorejs.org/#debounce

luisherranz avatar May 08 '15 09:05 luisherranz