How to some actions data to many stores?
For example, I got some post data from server in user action.
So this is simple psudo action code.
class UserActions {
getPosts() {
asyncFetch(apiEndPoint, function(data) {
/*
* data : {
* PostStore : [ ... ],
* UserStore : { ... },
* CommentStore : [ ... ],
* AppDataStore : { ... },
* StatusDataStore : { ... },
* ...
* }
*
*/
PostActions.receiveStoreData(data.PostStore);
UserActions.receiveStoreData(data.UserStore);
CommentActions.receiveStoreData(data.CommentStore);
AppDataActions.receiveStoreData(data.AppDataStore);
StatusActions.receiveStoreData(data.StatusDataStore);
...
}
}
}
I'm curious about setting many store data into the each stores calling actions in the action.
How to fix it with best practice?
Your action creator should use the dispatcher to dispatch the corresponding action as below:
import { Dispatcher } from 'flux';
class UserActions {
getPosts() {
asyncFetch(apiEndPoint, function(data) {
const action = {
type: 'ADD_POSTS',
data
};
Dispatcher.dispatch(action);
}
}
// ...
}
Then one or more store can register to the dispatcher and listen to the same ADD_POSTS
action:
import { EventEmitter } from 'events';
let posts = [];
const PostStore = Object.assign({}, EventEmitter.prototype, {
dispatcherIndex: AppDispatcher.register(action => {
const { type, data } = action;
switch (type) {
case 'ADD_POSTS':
posts = posts.concat(data);
PostStore.emitChange();
break;
// ...
}
return true;
});
emitChange() {
this.emit('change');
}
// ...
});