UNPKG

10.4 kBJavaScriptView Raw
1import $$observable from 'symbol-observable'
2
3import ActionTypes from './utils/actionTypes'
4import isPlainObject from './utils/isPlainObject'
5
6/**
7 * Creates a Redux store that holds the state tree.
8 * The only way to change the data in the store is to call `dispatch()` on it.
9 *
10 * There should only be a single store in your app. To specify how different
11 * parts of the state tree respond to actions, you may combine several reducers
12 * into a single reducer function by using `combineReducers`.
13 *
14 * @param {Function} reducer A function that returns the next state tree, given
15 * the current state tree and the action to handle.
16 *
17 * @param {any} [preloadedState] The initial state. You may optionally specify it
18 * to hydrate the state from the server in universal apps, or to restore a
19 * previously serialized user session.
20 * If you use `combineReducers` to produce the root reducer function, this must be
21 * an object with the same shape as `combineReducers` keys.
22 *
23 * @param {Function} [enhancer] The store enhancer. You may optionally specify it
24 * to enhance the store with third-party capabilities such as middleware,
25 * time travel, persistence, etc. The only store enhancer that ships with Redux
26 * is `applyMiddleware()`.
27 *
28 * @returns {Store} A Redux store that lets you read the state, dispatch actions
29 * and subscribe to changes.
30 */
31export default function createStore(reducer, preloadedState, enhancer) {
32 if (
33 (typeof preloadedState === 'function' && typeof enhancer === 'function') ||
34 (typeof enhancer === 'function' && typeof arguments[3] === 'function')
35 ) {
36 throw new Error(
37 'It looks like you are passing several store enhancers to ' +
38 'createStore(). This is not supported. Instead, compose them ' +
39 'together to a single function.'
40 )
41 }
42
43 if (typeof preloadedState === 'function' && typeof enhancer === 'undefined') {
44 enhancer = preloadedState
45 preloadedState = undefined
46 }
47
48 if (typeof enhancer !== 'undefined') {
49 if (typeof enhancer !== 'function') {
50 throw new Error('Expected the enhancer to be a function.')
51 }
52
53 return enhancer(createStore)(reducer, preloadedState)
54 }
55
56 if (typeof reducer !== 'function') {
57 throw new Error('Expected the reducer to be a function.')
58 }
59
60 let currentReducer = reducer
61 let currentState = preloadedState
62 let currentListeners = []
63 let nextListeners = currentListeners
64 let isDispatching = false
65
66 /**
67 * This makes a shallow copy of currentListeners so we can use
68 * nextListeners as a temporary list while dispatching.
69 *
70 * This prevents any bugs around consumers calling
71 * subscribe/unsubscribe in the middle of a dispatch.
72 */
73 function ensureCanMutateNextListeners() {
74 if (nextListeners === currentListeners) {
75 nextListeners = currentListeners.slice()
76 }
77 }
78
79 /**
80 * Reads the state tree managed by the store.
81 *
82 * @returns {any} The current state tree of your application.
83 */
84 function getState() {
85 if (isDispatching) {
86 throw new Error(
87 'You may not call store.getState() while the reducer is executing. ' +
88 'The reducer has already received the state as an argument. ' +
89 'Pass it down from the top reducer instead of reading it from the store.'
90 )
91 }
92
93 return currentState
94 }
95
96 /**
97 * Adds a change listener. It will be called any time an action is dispatched,
98 * and some part of the state tree may potentially have changed. You may then
99 * call `getState()` to read the current state tree inside the callback.
100 *
101 * You may call `dispatch()` from a change listener, with the following
102 * caveats:
103 *
104 * 1. The subscriptions are snapshotted just before every `dispatch()` call.
105 * If you subscribe or unsubscribe while the listeners are being invoked, this
106 * will not have any effect on the `dispatch()` that is currently in progress.
107 * However, the next `dispatch()` call, whether nested or not, will use a more
108 * recent snapshot of the subscription list.
109 *
110 * 2. The listener should not expect to see all state changes, as the state
111 * might have been updated multiple times during a nested `dispatch()` before
112 * the listener is called. It is, however, guaranteed that all subscribers
113 * registered before the `dispatch()` started will be called with the latest
114 * state by the time it exits.
115 *
116 * @param {Function} listener A callback to be invoked on every dispatch.
117 * @returns {Function} A function to remove this change listener.
118 */
119 function subscribe(listener) {
120 if (typeof listener !== 'function') {
121 throw new Error('Expected the listener to be a function.')
122 }
123
124 if (isDispatching) {
125 throw new Error(
126 'You may not call store.subscribe() while the reducer is executing. ' +
127 'If you would like to be notified after the store has been updated, subscribe from a ' +
128 'component and invoke store.getState() in the callback to access the latest state. ' +
129 'See https://redux.js.org/api-reference/store#subscribelistener for more details.'
130 )
131 }
132
133 let isSubscribed = true
134
135 ensureCanMutateNextListeners()
136 nextListeners.push(listener)
137
138 return function unsubscribe() {
139 if (!isSubscribed) {
140 return
141 }
142
143 if (isDispatching) {
144 throw new Error(
145 'You may not unsubscribe from a store listener while the reducer is executing. ' +
146 'See https://redux.js.org/api-reference/store#subscribelistener for more details.'
147 )
148 }
149
150 isSubscribed = false
151
152 ensureCanMutateNextListeners()
153 const index = nextListeners.indexOf(listener)
154 nextListeners.splice(index, 1)
155 currentListeners = null
156 }
157 }
158
159 /**
160 * Dispatches an action. It is the only way to trigger a state change.
161 *
162 * The `reducer` function, used to create the store, will be called with the
163 * current state tree and the given `action`. Its return value will
164 * be considered the **next** state of the tree, and the change listeners
165 * will be notified.
166 *
167 * The base implementation only supports plain object actions. If you want to
168 * dispatch a Promise, an Observable, a thunk, or something else, you need to
169 * wrap your store creating function into the corresponding middleware. For
170 * example, see the documentation for the `redux-thunk` package. Even the
171 * middleware will eventually dispatch plain object actions using this method.
172 *
173 * @param {Object} action A plain object representing “what changed”. It is
174 * a good idea to keep actions serializable so you can record and replay user
175 * sessions, or use the time travelling `redux-devtools`. An action must have
176 * a `type` property which may not be `undefined`. It is a good idea to use
177 * string constants for action types.
178 *
179 * @returns {Object} For convenience, the same action object you dispatched.
180 *
181 * Note that, if you use a custom middleware, it may wrap `dispatch()` to
182 * return something else (for example, a Promise you can await).
183 */
184 function dispatch(action) {
185 if (!isPlainObject(action)) {
186 throw new Error(
187 'Actions must be plain objects. ' +
188 'Use custom middleware for async actions.'
189 )
190 }
191
192 if (typeof action.type === 'undefined') {
193 throw new Error(
194 'Actions may not have an undefined "type" property. ' +
195 'Have you misspelled a constant?'
196 )
197 }
198
199 if (isDispatching) {
200 throw new Error('Reducers may not dispatch actions.')
201 }
202
203 try {
204 isDispatching = true
205 currentState = currentReducer(currentState, action)
206 } finally {
207 isDispatching = false
208 }
209
210 const listeners = (currentListeners = nextListeners)
211 for (let i = 0; i < listeners.length; i++) {
212 const listener = listeners[i]
213 listener()
214 }
215
216 return action
217 }
218
219 /**
220 * Replaces the reducer currently used by the store to calculate the state.
221 *
222 * You might need this if your app implements code splitting and you want to
223 * load some of the reducers dynamically. You might also need this if you
224 * implement a hot reloading mechanism for Redux.
225 *
226 * @param {Function} nextReducer The reducer for the store to use instead.
227 * @returns {void}
228 */
229 function replaceReducer(nextReducer) {
230 if (typeof nextReducer !== 'function') {
231 throw new Error('Expected the nextReducer to be a function.')
232 }
233
234 currentReducer = nextReducer
235
236 // This action has a similiar effect to ActionTypes.INIT.
237 // Any reducers that existed in both the new and old rootReducer
238 // will receive the previous state. This effectively populates
239 // the new state tree with any relevant data from the old one.
240 dispatch({ type: ActionTypes.REPLACE })
241 }
242
243 /**
244 * Interoperability point for observable/reactive libraries.
245 * @returns {observable} A minimal observable of state changes.
246 * For more information, see the observable proposal:
247 * https://github.com/tc39/proposal-observable
248 */
249 function observable() {
250 const outerSubscribe = subscribe
251 return {
252 /**
253 * The minimal observable subscription method.
254 * @param {Object} observer Any object that can be used as an observer.
255 * The observer object should have a `next` method.
256 * @returns {subscription} An object with an `unsubscribe` method that can
257 * be used to unsubscribe the observable from the store, and prevent further
258 * emission of values from the observable.
259 */
260 subscribe(observer) {
261 if (typeof observer !== 'object' || observer === null) {
262 throw new TypeError('Expected the observer to be an object.')
263 }
264
265 function observeState() {
266 if (observer.next) {
267 observer.next(getState())
268 }
269 }
270
271 observeState()
272 const unsubscribe = outerSubscribe(observeState)
273 return { unsubscribe }
274 },
275
276 [$$observable]() {
277 return this
278 }
279 }
280 }
281
282 // When a store is created, an "INIT" action is dispatched so that every
283 // reducer returns their initial state. This effectively populates
284 // the initial state tree.
285 dispatch({ type: ActionTypes.INIT })
286
287 return {
288 dispatch,
289 subscribe,
290 getState,
291 replaceReducer,
292 [$$observable]: observable
293 }
294}