Last active
August 29, 2015 14:25
-
-
Save mistadikay/85d243fd1f4610412759 to your computer and use it in GitHub Desktop.
Declarative data fetching in React components with Baobab
This file contains hidden or 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
| import { Component } from 'react'; | |
| import DataWatcher from 'components/@data-watcher'; | |
| // DataWatcher decorator watches data paths described below | |
| // and updates local state whenever global state changes something in these paths | |
| @DataWatcher | |
| class Product extends Component { | |
| static displayName = 'Product'; | |
| // data paths can be static or they can contain props and states | |
| // this gives us lots of flexibility | |
| static data = (props, state) => ({ | |
| details: [ | |
| 'data', | |
| 'products', | |
| 'details', | |
| props._productID | |
| ] | |
| }); | |
| // since data paths can contain props or state | |
| // DataWatcher must be reloaded on every update to make sure we have the relevant data | |
| componentWillReceiveProps(nextProps) { | |
| if (nextProps._productID !== this.props._productID) { | |
| this._reloadData(nextProps); | |
| } | |
| } | |
| // since data is just in local state of the component | |
| // we can work with it and not care about when and from where it will be delivered | |
| render() { | |
| const details = this.state.data.details; | |
| if (!details) { | |
| return null; | |
| } | |
| return ( | |
| <div className='product'> | |
| { | |
| Object.keys(details).map(key => ( | |
| <div className='product__property' key={ key }> | |
| { details[key] } | |
| </div> | |
| )) | |
| } | |
| </div> | |
| ) | |
| } | |
| }; | |
| export default Product; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment