Skip to content

Instantly share code, notes, and snippets.

@itrelease
Forked from gaearon/Stateful.js
Last active August 29, 2015 14:19

Revisions

  1. @gaearon gaearon created this gist Apr 23, 2015.
    57 changes: 57 additions & 0 deletions Stateful.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,57 @@
    import React, { Component } from 'react';

    // Usage:
    //
    // @Stateful({
    // initialize(props) {
    // return {
    // count: 0
    // };
    // },

    // reducers: {
    // increment(props, state) {
    // return {
    // count: state.count + 1
    // };
    // }
    // }
    // })
    // class Counter {
    // static propTypes = {
    // count: PropTypes.number.isRequired,
    // increment: PropTypes.func.isRequired
    // };

    // render() {
    // const { count, increment } = this.props;
    // return (
    // <button onClick={increment}>
    // Pressed {count} times.
    // </button>
    // )
    // }
    // }

    export default function Stateful({ initialize, reducers }) {
    return DecoratedComponent => class StateContainer extends Component {
    constructor(props) {
    super(props);
    this.state = initialize(props);

    this.reducers = {};
    Object.keys(reducers).forEach(key => {
    this.reducers[key] = (...args) => {
    const nextState = reducers[key](this.props, this.state, ...args);
    this.setState(nextState);
    }
    });
    }

    render() {
    return <DecoratedComponent {...this.props}
    {...this.state}
    {...this.reducers} />;
    }
    }
    }