I am using the flux-pattern and the flux dispatcher. I need to return a value from 'TextStore' to an action after creating a new TextItem because I need to reference it in another store. Here is a very simple version of what I want to do:
// stores.ts
var TextStore = {
add(){
// here I want to return a new ID
return createRandomID();
}
...
}
var ModuleStore = {
labelTextID; // refers to `id` on Text
...
}
// moduleactions.ts
...
import PageActions from './PageActions';
var ModuleActions = {
add: function (module) {
var textID = PageActions.add(); // here I need to get the ID of the newly create `Text`
module.labelTextID = textID;
Dispatcher.dispatch({
action: 'ADD_MODULE',
module: module
})
},
...
}
Now when I add a new Module
via dispatching an action, I want to create a new Text
as well and return its newly created ID from the store before.
The most obvious way would be to require the TextStore
inside ModuleActions
and call add()
directly. Is that against the flux-pattern?
Is there any way to accomplish that, maybe with promises? Sending callbacks via the dispatcher to the store doesnt work, because I cannot dispatch while another dispatch is unfinished.
Would be great if you guys can help me!
Calling the Store's method directly is an anti-pattern for Flux. If you directly call
TextStore.add()
then you are not following theAction -> Dispatcher -> Store --> View --> Action
cycle.In flux, the data should always generate in the
action
. This makes more sense when the process of generation of data is aync. In your case you were able to get around this because generation of data is not async. You are directly generating the data in the TextStore and then worrying about how to return that value.In your case generate the
id
in the action as you would have done if it was an async backend event, then pass thatid
down to theTextStore
via dispatcher and after that also pass the same id to theModuleStore
via the dispatcher.You could also break this down into further smaller, more specific actions. I kept it as-is so I could highlight the one line you should change.
You can have your async call
PageActions.add();
before you dispatch theModuleActions.add
and pass the returned value as a parameter toModuleActions.add