diff --git a/src/unstated.js b/src/unstated.js index 6955ee0..e25236e 100644 --- a/src/unstated.js +++ b/src/unstated.js @@ -64,25 +64,46 @@ export type SubscribeProps = { ) => Node }; -type SubscribeState = {}; +type SubscribeUpdaterProps = { + instances: Array, + children: ( + ...instances: $TupleMap(Class | C) => C> + ) => Node +}; +type SubscribeUpdaterState = {}; const DUMMY_STATE = {}; -export class Subscribe extends React.Component< - SubscribeProps, - SubscribeState +class SubscribeUpdater extends React.Component< + SubscribeUpdaterProps, + SubscribeUpdaterState > { state = {}; - instances: Array = []; unmounted = false; + componentDidMount() { + this._subscribe(this.props.instances); + } + componentWillUnmount() { this.unmounted = true; - this._unsubscribe(); + this._unsubscribe(this.props.instances); + } + + componentDidUpdate(prevProps: SubscribeUpdaterProps) { + this._unsubscribe(prevProps.instances); + this._subscribe(this.props.instances); } - _unsubscribe() { - this.instances.forEach(container => { + _subscribe(instances: Array) { + instances.forEach(container => { + container.unsubscribe(this.onUpdate); + container.subscribe(this.onUpdate); + }); + } + + _unsubscribe(instances: Array) { + instances.forEach(container => { container.unsubscribe(this.onUpdate); }); } @@ -97,12 +118,18 @@ export class Subscribe extends React.Component< }); }; + render() { + return this.props.children.apply(null, this.props.instances); + } +} + +export class Subscribe extends React.Component< + SubscribeProps +> { _createInstances( map: ContainerMapType | null, containers: ContainersType ): Array { - this._unsubscribe(); - if (map === null) { throw new Error( 'You must wrap your components with a ' @@ -110,7 +137,7 @@ export class Subscribe extends React.Component< } let safeMap = map; - let instances = containers.map(ContainerItem => { + return containers.map(ContainerItem => { let instance; if ( @@ -127,25 +154,20 @@ export class Subscribe extends React.Component< } } - instance.unsubscribe(this.onUpdate); - instance.subscribe(this.onUpdate); - return instance; }); - - this.instances = instances; - return instances; } render() { return ( - {map => - this.props.children.apply( - null, - this._createInstances(map, this.props.to) - ) - } + {map => ( + + {this.props.children} + + )} ); }