flummox icon indicating copy to clipboard operation
flummox copied to clipboard

Better explanation of how to pass dependencies between stores and actions

Open acdlite opened this issue 10 years ago • 5 comments

The answer is to use the Flux class to pass arguments to Actions and Store constructors.

acdlite avatar Feb 08 '15 21:02 acdlite

Riiight! I'm just making my first action class and wondering how to notify the store of some state that needs to update because of this action. But the trick is to have some helper function on the flux class that in turn will use the action and then update the corresponding stores state...? Am I confused? I feel confused :stuck_out_tongue_winking_eye:

//cc @acdlite

asbjornenge avatar Feb 18 '15 08:02 asbjornenge

Ok, now I'm getting that Store#setState() called from outside an action handler. :confused:

Here is my (really basic) usecase:

I have a store of :turtle:. I would like to add more :turtle: :turtle: . Store is created, FluxComponent is wrapping, so I have access for the flux object and to my current state.

How do I hook up an action to update my store with some more :turtle:?

asbjornenge avatar Feb 18 '15 09:02 asbjornenge

Haha nice :turtle:s.

Actions don't update stores directly. They send values through the dispatcher. In normal Flux, you'd use Dispatcher.dispatch(). In the Flummox, the return value of an action is automatically dispatched for you.

Stores can register to respond to actions using Store#register(). In order to do that, they need to be able to reference the actions they're interested in. So the recommended pattern is to pass the Flux instance to the constructor of the store and get the actions from there.

class TurtleStore extends Store {
  constructor(flux) {
    let turtleActions = flux.getActions('turtles');
    this.register(turtleActions.createTurtle, this.handleCreateTurtle);
  }

  handleCreateTurtle(newTurtle) {...}
}

acdlite avatar Feb 18 '15 13:02 acdlite

Aha! Superb :rocket: Hooked up and works like a charm. No more warnings :smile:

Figured it was something I overlooked. Others might struggle too, so consider adding to docs (if it's not just something I overlooked, that is a huge possibility) :wink: :see_no_evil:

Anyway, thanks for helping :turtle: :wave:

asbjornenge avatar Feb 18 '15 13:02 asbjornenge

No problem! Yes I agree, the docs need to be clearer.

acdlite avatar Feb 18 '15 14:02 acdlite