Search code examples
fluxreactjs-flux

Difference between dispatch and emit in Flux/React Native


I'm new in Flux/React Native.

I'm quite confused about dispatch vs emit using in Flux.

What is the main difference between them? And what happen when I use same Action Type in dispatch and emit.

For example:

Dispatcher.dispatch({
    actionType: 'ACTION1'
});
SomeStore.emit('ACTION1');

Solution

  • In Flux, events are emitted by the store indicating a change in its state. This 'change' event is listened to by views. This will prompt a view to fetch new state from the store. Mind you, the event never contains payload / information about the new state. It is really just what it reads - an event.

    Actions are slightly different. While they are indeed events, they are things that occur in our domain eg., Add item to cart. And they carry a payload that contains information about the action, eg.,

        {
          id: ‘add-item-to-cart’,
          payload: {
            cartId: 123,
            itemId: 1234,
            name: ‘Box of chocolates’,
            quantity: 1
          }
        }
    

    Actions are 'dispatched' from the views and the store(s) responds to the dispatch by possibly changing its state and emitting a 'change' event.

    So basically:

    1. A view dispatches an action with a payload (usually due to a user interaction) via the dispatcher
    2. The store (which had previously registered itself with the dispatcher)
      is notified of the action and uses the payload to change its state and emit an event.
    3. The view (which had previously registered itself with the store) is notified of the change event which causes it to get the new state from the store and change itself.

    So that's the difference. And about the question "use same Action Type in dispatch and emit", it doesn't really make sense, does it?

    I suggest you read this blog post - http://blog.andrewray.me/flux-for-stupid-people/ (The title means no offence BTW :))

    You already know this, but I'll say it again: A unidirectional data flow is central to the Flux pattern. That means data (not control) always flows in one direction.