-
-
Save edrpls/2ff0caf2cdf1bd36028a560c1d95fa2d 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 | |
// Creates an instance of a flux store, will be replaced later | |
import Store from './Store'; | |
// Some helpers to handle async calls | |
import * as http from './helpers/http'; | |
// Instance of a flux store, more on that later | |
import Store from './Store'; | |
// Flux dispatcher | |
import Dispatcher from 'flux/lib/Dispatcher'; | |
// Instance of flux dispatcher | |
const AppDispatcher = new Dispatcher(); | |
// store's state | |
let _state = { | |
clients: [] | |
}; | |
// the store | |
class ClientStore extends Store { | |
getState() { | |
return _state; | |
} | |
} | |
// Create a new 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 actions and define how handle them | |
clientStoreInstance.dispatchToken = AppDispatcher.register(async action => { | |
switch (action.actionType) { | |
case 'GET_CLIENTS': | |
await getClients(); | |
break; | |
case 'TOGGLE_SORTING': | |
await toggleSorting(); | |
break; | |
} | |
// Notify of the store change | |
clientStoreInstance.emitChange(); | |
}); | |
// Export the new instance of the store | |
export default clientStoreInstance; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment