diff --git a/package.json b/package.json index 1e1575a..5e2c445 100644 --- a/package.json +++ b/package.json @@ -22,11 +22,9 @@ "typescript": "tsc -p tsconfig.json" }, "dependencies": { - "create-react-context": "^0.1.5", - "tickedoff": "^1.0.1" + "create-react-context": "^0.1.5" }, "peerDependencies": { - "prop-types": "^15.5.0", "react": "^15.0.0 || ^16.0.0" }, "devDependencies": { diff --git a/src/unstated.d.ts b/src/unstated.d.ts index 17ea382..01ea00c 100644 --- a/src/unstated.d.ts +++ b/src/unstated.d.ts @@ -3,11 +3,13 @@ import * as React from 'react'; export class Container { state: State; setState( - state: ((prevState: Readonly) => (Partial | State | null)) | (Partial | State | null), + state: + | ((prevState: Readonly) => Partial | State | null) + | (Partial | State | null), callback?: () => void - ): void; - subscribe(fn: Function): void; - unsubscribe(fn: Function): void; + ): Promise; + subscribe(fn: () => any): void; + unsubscribe(fn: () => any): void; } export interface ContainerType { diff --git a/src/unstated.js b/src/unstated.js index c8a5778..199bd78 100644 --- a/src/unstated.js +++ b/src/unstated.js @@ -1,10 +1,8 @@ // @flow import React, { type Node } from 'react'; import createReactContext from 'create-react-context'; -import PropTypes from 'prop-types'; -import defer from 'tickedoff'; -type Listener = (cb?: () => void) => void; +type Listener = () => mixed; const StateContext = createReactContext(null); @@ -19,8 +17,8 @@ export class Container { setState( updater: $Shape | ((prevState: $Shape) => $Shape), callback?: () => void - ) { - defer(() => { + ): Promise { + return Promise.resolve().then(() => { let nextState; if (typeof updater === 'function') { @@ -36,23 +34,12 @@ export class Container { this.state = Object.assign({}, this.state, nextState); - let completed = 0; - let total = this._listeners.length; + let promises = this._listeners.map(listener => listener()); - this._listeners.forEach(fn => { - if (!callback) { - fn(); - return; + return Promise.all(promises).then(() => { + if (callback) { + return callback(); } - - let safeCallback = callback; - - fn(() => { - completed++; - if (completed < total) { - safeCallback(); - } - }); }); }); } @@ -85,11 +72,6 @@ export class Subscribe extends React.Component< SubscribeProps, SubscribeState > { - static propTypes = { - to: PropTypes.array.isRequired, - children: PropTypes.func.isRequired - }; - state = {}; instances: Array = []; @@ -103,8 +85,10 @@ export class Subscribe extends React.Component< }); } - onUpdate: Listener = cb => { - this.setState(DUMMY_STATE, cb); + onUpdate: Listener = () => { + return new Promise(resolve => { + this.setState(DUMMY_STATE, resolve); + }); }; _createInstances(