Skip to content

Instantly share code, notes, and snippets.

@iam4x
Last active October 9, 2015 22:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iam4x/385d9c15b0dcd1ae2476 to your computer and use it in GitHub Desktop.
Save iam4x/385d9c15b0dcd1ae2476 to your computer and use it in GitHub Desktop.
`connectToStores` decorator for https://github.com/goatslacker/alt

connecToStores.jsx

import React, { Component, PropTypes } from 'react';

export default function connectToStores(reducer) {
  return function(DecoratedComponent) {
    return class ConnectToStoresWrapper extends Component {
      static contextTypes = { flux: PropTypes.object.isRequired }

      constructor(props, context) {
        super(props, context);
        const { flux } = this.context;
        const finalState = JSON.parse(flux.takeSnapshot());
        this.state = { customProps: reducer(finalState) };
      }

      componentDidMount() {
        const { flux } = this.context;
        flux.FinalStore.listen(this.handleStoresChange);
      }

      componentWillUnmount() {
        const { flux } = this.context;
        flux.FinalStore.unlisten(this.handleStoresChange);
      }

      handleStoresChange = () => {
        const { flux } = this.context;
        const finalState = JSON.parse(flux.takeSnapshot());
        return this.setState({ customProps: reducer(finalState) });
      }

      render() {
        const { customProps } = this.state;
        return (<DecoratedComponent { ...this.props } { ...customProps } />);
      }
    };
  };
}

Usage

It's based on react-redux connect decorator

import React, { Component, PropTypes } from 'react';
import connectToStores from './connectToStores';

@connectToStores(({ session: { currentUser } }) => ({ currentUser })
class Example extends Component {

  static propTypes = { currentUser: PropTypes.object.isRequired }
  
  render() {
    const { currentUser } = this.props;
    
    return (
      <pre>{ JSON.stringify(currentUser, null, 4)</pre>
    );
  }

}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment