Skip to content

Commit d4f8cb9

Browse files
committed
Proof of concept: enhancer overhaul
1 parent 52fb473 commit d4f8cb9

File tree

4 files changed

+83
-197
lines changed

4 files changed

+83
-197
lines changed

src/applyMiddleware.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ import compose from './compose'
1919
export default function applyMiddleware(...middlewares) {
2020
return (createStore) => (reducer, initialState, enhancer) => {
2121
var store = createStore(reducer, initialState, enhancer)
22-
var dispatch = store.dispatch
22+
var dispatch
2323
var chain = []
2424

2525
var middlewareAPI = {

src/createStore.js

Lines changed: 66 additions & 172 deletions
Original file line numberDiff line numberDiff line change
@@ -1,234 +1,122 @@
11
import isPlainObject from 'lodash/isPlainObject'
2+
import warning from './utils/warning'
23
import $$observable from 'symbol-observable'
34

4-
/**
5-
* These are private action types reserved by Redux.
6-
* For any unknown actions, you must return the current state.
7-
* If the current state is undefined, you must return the initial state.
8-
* Do not reference these action types directly in your code.
9-
*/
105
export var ActionTypes = {
116
INIT: '@@redux/INIT'
127
}
138

14-
/**
15-
* Creates a Redux store that holds the state tree.
16-
* The only way to change the data in the store is to call `dispatch()` on it.
17-
*
18-
* There should only be a single store in your app. To specify how different
19-
* parts of the state tree respond to actions, you may combine several reducers
20-
* into a single reducer function by using `combineReducers`.
21-
*
22-
* @param {Function} reducer A function that returns the next state tree, given
23-
* the current state tree and the action to handle.
24-
*
25-
* @param {any} [initialState] The initial state. You may optionally specify it
26-
* to hydrate the state from the server in universal apps, or to restore a
27-
* previously serialized user session.
28-
* If you use `combineReducers` to produce the root reducer function, this must be
29-
* an object with the same shape as `combineReducers` keys.
30-
*
31-
* @param {Function} enhancer The store enhancer. You may optionally specify it
32-
* to enhance the store with third-party capabilities such as middleware,
33-
* time travel, persistence, etc. The only store enhancer that ships with Redux
34-
* is `applyMiddleware()`.
35-
*
36-
* @returns {Store} A Redux store that lets you read the state, dispatch actions
37-
* and subscribe to changes.
38-
*/
39-
export default function createStore(reducer, initialState, enhancer) {
40-
if (typeof initialState === 'function' && typeof enhancer === 'undefined') {
41-
enhancer = initialState
42-
initialState = undefined
9+
function createBasicStore(reducer, initialState, onChange) {
10+
var currentState = initialState
11+
var isDispatching = false
12+
13+
function getState() {
14+
return currentState
4315
}
4416

45-
if (typeof enhancer !== 'undefined') {
46-
if (typeof enhancer !== 'function') {
47-
throw new Error('Expected the enhancer to be a function.')
17+
function dispatch(action) {
18+
if (!isPlainObject(action)) {
19+
throw new Error(
20+
'Actions must be plain objects. ' +
21+
'Use custom middleware for async actions.'
22+
)
23+
}
24+
if (typeof action.type === 'undefined') {
25+
throw new Error(
26+
'Actions may not have an undefined "type" property. ' +
27+
'Have you misspelled a constant?'
28+
)
29+
}
30+
if (isDispatching) {
31+
throw new Error('Reducers may not dispatch actions.')
4832
}
33+
try {
34+
isDispatching = true
35+
currentState = reducer(currentState, action)
36+
} finally {
37+
isDispatching = false
38+
}
39+
onChange()
40+
return action
41+
}
4942

50-
return enhancer(createStore)(reducer, initialState)
43+
return {
44+
dispatch,
45+
getState,
5146
}
47+
}
5248

49+
export default function createEnhancedStore(reducer, initialState, enhancer) {
5350
if (typeof reducer !== 'function') {
5451
throw new Error('Expected the reducer to be a function.')
5552
}
53+
if (typeof initialState === 'function' && typeof enhancer === 'undefined') {
54+
enhancer = initialState
55+
initialState = undefined
56+
}
57+
var createStore = createBasicStore
58+
if (typeof enhancer !== 'undefined') {
59+
if (typeof enhancer !== 'function') {
60+
throw new Error('Expected the enhancer to be a function.')
61+
}
62+
createStore = enhancer(createBasicStore)
63+
}
5664

57-
var currentReducer = reducer
58-
var currentState = initialState
65+
var store
5966
var currentListeners = []
6067
var nextListeners = currentListeners
61-
var isDispatching = false
6268

6369
function ensureCanMutateNextListeners() {
6470
if (nextListeners === currentListeners) {
6571
nextListeners = currentListeners.slice()
6672
}
6773
}
68-
69-
/**
70-
* Reads the state tree managed by the store.
71-
*
72-
* @returns {any} The current state tree of your application.
73-
*/
74-
function getState() {
75-
return currentState
76-
}
77-
78-
/**
79-
* Adds a change listener. It will be called any time an action is dispatched,
80-
* and some part of the state tree may potentially have changed. You may then
81-
* call `getState()` to read the current state tree inside the callback.
82-
*
83-
* You may call `dispatch()` from a change listener, with the following
84-
* caveats:
85-
*
86-
* 1. The subscriptions are snapshotted just before every `dispatch()` call.
87-
* If you subscribe or unsubscribe while the listeners are being invoked, this
88-
* will not have any effect on the `dispatch()` that is currently in progress.
89-
* However, the next `dispatch()` call, whether nested or not, will use a more
90-
* recent snapshot of the subscription list.
91-
*
92-
* 2. The listener should not expect to see all state changes, as the state
93-
* might have been updated multiple times during a nested `dispatch()` before
94-
* the listener is called. It is, however, guaranteed that all subscribers
95-
* registered before the `dispatch()` started will be called with the latest
96-
* state by the time it exits.
97-
*
98-
* @param {Function} listener A callback to be invoked on every dispatch.
99-
* @returns {Function} A function to remove this change listener.
100-
*/
10174
function subscribe(listener) {
10275
if (typeof listener !== 'function') {
10376
throw new Error('Expected listener to be a function.')
10477
}
105-
10678
var isSubscribed = true
107-
10879
ensureCanMutateNextListeners()
10980
nextListeners.push(listener)
110-
11181
return function unsubscribe() {
11282
if (!isSubscribed) {
11383
return
11484
}
115-
11685
isSubscribed = false
117-
11886
ensureCanMutateNextListeners()
11987
var index = nextListeners.indexOf(listener)
12088
nextListeners.splice(index, 1)
12189
}
12290
}
12391

124-
/**
125-
* Dispatches an action. It is the only way to trigger a state change.
126-
*
127-
* The `reducer` function, used to create the store, will be called with the
128-
* current state tree and the given `action`. Its return value will
129-
* be considered the **next** state of the tree, and the change listeners
130-
* will be notified.
131-
*
132-
* The base implementation only supports plain object actions. If you want to
133-
* dispatch a Promise, an Observable, a thunk, or something else, you need to
134-
* wrap your store creating function into the corresponding middleware. For
135-
* example, see the documentation for the `redux-thunk` package. Even the
136-
* middleware will eventually dispatch plain object actions using this method.
137-
*
138-
* @param {Object} action A plain object representing “what changed”. It is
139-
* a good idea to keep actions serializable so you can record and replay user
140-
* sessions, or use the time travelling `redux-devtools`. An action must have
141-
* a `type` property which may not be `undefined`. It is a good idea to use
142-
* string constants for action types.
143-
*
144-
* @returns {Object} For convenience, the same action object you dispatched.
145-
*
146-
* Note that, if you use a custom middleware, it may wrap `dispatch()` to
147-
* return something else (for example, a Promise you can await).
148-
*/
14992
function dispatch(action) {
150-
if (!isPlainObject(action)) {
151-
throw new Error(
152-
'Actions must be plain objects. ' +
153-
'Use custom middleware for async actions.'
154-
)
155-
}
156-
157-
if (typeof action.type === 'undefined') {
158-
throw new Error(
159-
'Actions may not have an undefined "type" property. ' +
160-
'Have you misspelled a constant?'
161-
)
162-
}
163-
164-
if (isDispatching) {
165-
throw new Error('Reducers may not dispatch actions.')
166-
}
167-
168-
try {
169-
isDispatching = true
170-
currentState = currentReducer(currentState, action)
171-
} finally {
172-
isDispatching = false
173-
}
93+
return store.dispatch(action)
94+
}
17495

96+
function onChange() {
17597
var listeners = currentListeners = nextListeners
17698
for (var i = 0; i < listeners.length; i++) {
17799
listeners[i]()
178100
}
179-
180-
return action
181101
}
182102

183-
/**
184-
* Replaces the reducer currently used by the store to calculate the state.
185-
*
186-
* You might need this if your app implements code splitting and you want to
187-
* load some of the reducers dynamically. You might also need this if you
188-
* implement a hot reloading mechanism for Redux.
189-
*
190-
* @param {Function} nextReducer The reducer for the store to use instead.
191-
* @returns {void}
192-
*/
193-
function replaceReducer(nextReducer) {
194-
if (typeof nextReducer !== 'function') {
195-
throw new Error('Expected the nextReducer to be a function.')
196-
}
197-
198-
currentReducer = nextReducer
199-
dispatch({ type: ActionTypes.INIT })
103+
function getState() {
104+
return store.getState()
200105
}
201106

202-
/**
203-
* Interoperability point for observable/reactive libraries.
204-
* @returns {observable} A minimal observable of state changes.
205-
* For more information, see the observable proposal:
206-
* https://github.com/zenparsing/es-observable
207-
*/
208107
function observable() {
209-
var outerSubscribe = subscribe
210108
return {
211-
/**
212-
* The minimal observable subscription method.
213-
* @param {Object} observer Any object that can be used as an observer.
214-
* The observer object should have a `next` method.
215-
* @returns {subscription} An object with an `unsubscribe` method that can
216-
* be used to unsubscribe the observable from the store, and prevent further
217-
* emission of values from the observable.
218-
*/
219109
subscribe(observer) {
220110
if (typeof observer !== 'object') {
221111
throw new TypeError('Expected the observer to be an object.')
222112
}
223-
224113
function observeState() {
225114
if (observer.next) {
226115
observer.next(getState())
227116
}
228117
}
229-
230118
observeState()
231-
var unsubscribe = outerSubscribe(observeState)
119+
var unsubscribe = subscribe(observeState)
232120
return { unsubscribe }
233121
},
234122

@@ -238,16 +126,22 @@ export default function createStore(reducer, initialState, enhancer) {
238126
}
239127
}
240128

241-
// When a store is created, an "INIT" action is dispatched so that every
242-
// reducer returns their initial state. This effectively populates
243-
// the initial state tree.
244-
dispatch({ type: ActionTypes.INIT })
129+
function replaceReducer(nextReducer) {
130+
if (typeof nextReducer !== 'function') {
131+
throw new Error('Expected the nextReducer to be a function.')
132+
}
133+
134+
store = createStore(nextReducer, store ? getState() : initialState, onChange)
135+
dispatch({ type: ActionTypes.INIT })
136+
}
137+
138+
replaceReducer(reducer)
245139

246140
return {
247141
dispatch,
248-
subscribe,
249142
getState,
143+
subscribe,
250144
replaceReducer,
251145
[$$observable]: observable
252146
}
253-
}
147+
}

test/applyMiddleware.spec.js

Lines changed: 0 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -94,22 +94,4 @@ describe('applyMiddleware', () => {
9494
done()
9595
})
9696
})
97-
98-
it('keeps unwrapped dispatch available while middleware is initializing', () => {
99-
// This is documenting the existing behavior in Redux 3.x.
100-
// We plan to forbid this in Redux 4.x.
101-
102-
function earlyDispatch({ dispatch }) {
103-
dispatch(addTodo('Hello'))
104-
return () => action => action
105-
}
106-
107-
const store = createStore(reducers.todos, applyMiddleware(earlyDispatch))
108-
expect(store.getState()).toEqual([
109-
{
110-
id: 1,
111-
text: 'Hello'
112-
}
113-
])
114-
})
11597
})

0 commit comments

Comments
 (0)