-
-
Save edrpls/fa64494fc1b0673a0c03ea1452064b54 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ClientStore.js | |
// Modified to instance directly from EventEmitter instead of Store for better control of its methods | |
// Removed flux Store class: "import Store from './Store';" | |
// will notify components when the store is updated | |
import EventEmitter from 'events'; | |
// helper that creates a flux store connected to a redux reducer | |
import createFluxStore from './createFluxStore'; | |
// the new reducer | |
import clientReducer from './clientsReducer'; | |
// Flux dispatcher | |
import Dispatcher from 'flux/lib/Dispatcher'; | |
// Constant used by the dispatcher to notify when data changed | |
const CHANGE_EVENT = 'change'; | |
// Instance of flux dispatcher | |
const AppDispatcher = new Dispatcher(); | |
// Redux store compatible with flux | |
const clientsReduxStore = createFluxStore(clientsReducer); | |
// Initial state will come from redux | |
let _state = clientsReduxStore.getState(); | |
// modified store, instance of EventEmitter | |
const ClientStore = Object.assign({}, EventEmitter.prototype, { | |
getState() { | |
return _state; | |
}, | |
emitChange() { | |
this.emit(CHANGE_EVENT); | |
}, | |
addChangeListener(callback) { | |
this.on(CHANGE_EVENT, callback); | |
}, | |
removeChangeListener(callback) { | |
this.removeListener(CHANGE_EVENT, callback); | |
}, | |
dispatcherIndex: AppDispatcher.register(function(payload) { | |
const action = { | |
...payload, | |
type: payload.actionType | |
}; | |
adminReduxStore.dispatch(action); | |
}) | |
} | |
// remove instance of the store: const clientStoreInstance = new ClientStore(); | |
// Async function that makes a server request to get all clients | |
// returns a Promise | |
const getClients = () => | |
http.get('/clients').then(clients => { | |
// Update the state with the successful server response | |
_state.clients = clients; | |
}); | |
// Toggles the direction of the results | |
const toggleSorting = () => { | |
_state.clients = _state.clients.reverse(); | |
}; | |
// listen for flux actions with the redux-flux store | |
clientsReduxStore.subscribe(async function(action) { | |
switch (action.actionType) { | |
case 'GET_CLIENTS': | |
await getClients(); | |
break; | |
case 'TOGGLE_SORTING': | |
await toggleSorting(); | |
break; | |
} | |
// Notify of the redux-flux store change | |
ClientStore.emitChange(); | |
}); | |
// Export the the redux-flux store | |
export default AdminStore; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment