mistadikay
7/20/2015 - 4:57 PM

Declarative data fetching in React components with Baobab

Declarative data fetching in React components with Baobab

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;