|
2 | 2 | import React, { type Node } from 'react'; |
3 | 3 | import createReactContext from 'create-react-context'; |
4 | 4 | import PropTypes from 'prop-types'; |
| 5 | +import defer from 'tickedoff'; |
| 6 | + |
| 7 | +type Listener = (cb?: () => void) => void; |
5 | 8 |
|
6 | 9 | const StateContext = createReactContext(null); |
7 | 10 |
|
8 | 11 | export class Container<State: {}> { |
9 | 12 | state: State; |
10 | | - _listeners: Array<() => mixed> = []; |
| 13 | + _listeners: Array<Listener> = []; |
| 14 | + |
| 15 | + setState( |
| 16 | + updater: $Shape<State> | ((prevState: $Shape<State>) => $Shape<State>), |
| 17 | + callback?: () => void |
| 18 | + ) { |
| 19 | + defer(() => { |
| 20 | + let nextState; |
| 21 | + |
| 22 | + if (typeof updater === 'function') { |
| 23 | + nextState = updater(this.state); |
| 24 | + } else { |
| 25 | + nextState = updater; |
| 26 | + } |
| 27 | + |
| 28 | + if (nextState == null) { |
| 29 | + if (callback) callback(); |
| 30 | + return; |
| 31 | + } |
11 | 32 |
|
12 | | - setState(state: $Shape<State>) { |
13 | | - this.state = Object.assign({}, this.state, state); |
14 | | - this._listeners.forEach(fn => fn()); |
| 33 | + this.state = Object.assign({}, this.state, nextState); |
| 34 | + |
| 35 | + let completed = 0; |
| 36 | + let total = this._listeners.length; |
| 37 | + |
| 38 | + this._listeners.forEach(fn => { |
| 39 | + if (!callback) { |
| 40 | + fn(); |
| 41 | + return; |
| 42 | + } |
| 43 | + |
| 44 | + let safeCallback = callback; |
| 45 | + |
| 46 | + fn(() => { |
| 47 | + completed++; |
| 48 | + if (completed < total) { |
| 49 | + safeCallback(); |
| 50 | + } |
| 51 | + }); |
| 52 | + }); |
| 53 | + }); |
15 | 54 | } |
16 | 55 |
|
17 | | - subscribe(fn: Function) { |
| 56 | + subscribe(fn: Listener) { |
18 | 57 | this._listeners.push(fn); |
19 | 58 | } |
20 | 59 |
|
21 | | - unsubscribe(fn: Function) { |
| 60 | + unsubscribe(fn: Listener) { |
22 | 61 | this._listeners = this._listeners.filter(f => f !== fn); |
23 | 62 | } |
24 | 63 | } |
@@ -60,16 +99,16 @@ export class Subscribe<Containers: ContainersType> extends React.Component< |
60 | 99 | }); |
61 | 100 | } |
62 | 101 |
|
63 | | - onUpdate = () => { |
64 | | - this.setState(DUMMY_STATE); |
| 102 | + onUpdate: Listener = cb => { |
| 103 | + this.setState(DUMMY_STATE, cb); |
65 | 104 | }; |
66 | 105 |
|
67 | 106 | _createInstances( |
68 | 107 | map: ContainerMapType | null, |
69 | 108 | containers: ContainersType |
70 | 109 | ): Array<ContainerType> { |
71 | 110 | this._unsubscribe(); |
72 | | - |
| 111 | + |
73 | 112 | if (map === null) { |
74 | 113 | throw new Error( |
75 | 114 | 'You must wrap your <Subscribe> components with a <Provider>' |
|
0 commit comments