Skip to content

Instantly share code, notes, and snippets.

@mistadikay
Last active August 29, 2015 14:25
Show Gist options
  • Save mistadikay/78e5882b7c5fa28c165a to your computer and use it in GitHub Desktop.
Save mistadikay/78e5882b7c5fa28c165a to your computer and use it in GitHub Desktop.
import { Component } from 'react';
// Flux action creators for products
import ProductsActions from 'actions/products';
// global state
import state from 'state';
// main wrapper component
class App extends Component {
static displayName = 'app';
constructor(props) {
super(props);
// whenever someone is trying to access data in these paths and it is not found
// we are requesting this missing data from the server
state.on('get',
[ 'data', 'products', 'details' ],
productID => ProductsActions.getProductInfo(productID)
);
state.on('get',
[ 'data', 'products', 'list' ],
sortOptions => ProductsActions.getProducts(sortOptions)
);
}
render() {
return (
<div className='app'>
...
</div>
);
}
}
export default App;
import Actions from '.';
// when data has been loaded from the server, we dispatch it as usual
class ProductsActions extends Actions {
dispatchProductInfoData(productID, data) {
this.dispatch('PRODUCT_INFO_LOADED', { productID, data });
}
dispatchProductInfoDataLoadError(productID, error) {
this.dispatch('PRODUCT_INFO_LOAD_ERROR', { productID, error });
}
getProductInfo(productID) {
this.api.getProductInfo(productID).then(
this.dispatchProductInfoData.bind(this, productID),
this.dispatchProductInfoDataLoadError.bind(this, productID)
);
}
}
export default new ProductsActions();
import state from 'state';
import Store from '.';
import constants from 'constants/actions';
// store puts data into the global state
class ProductsStore extends Store {
[constants.PRODUCT_INFO_LOADED]({ data }) {
state.getTree().set([ 'data', 'products', 'details', data.id ], data);
}
[constants.PRODUCT_INFO_LOAD_ERROR]({ productID, error }) {
this.emit(constants.PRODUCT_INFO_LOAD_ERROR, productID, error);
}
}
export default new ProductsStore();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment