UNPKG

17.5 kBPlain TextView Raw
1import $$observable from './utils/symbol-observable'
2
3import {
4 Store,
5 StoreEnhancer,
6 Dispatch,
7 Observer,
8 ListenerCallback,
9 UnknownIfNonSpecific
10} from './types/store'
11import { Action } from './types/actions'
12import { Reducer } from './types/reducers'
13import ActionTypes from './utils/actionTypes'
14import isPlainObject from './utils/isPlainObject'
15import { kindOf } from './utils/kindOf'
16
17/**
18 * @deprecated
19 *
20 * **We recommend using the `configureStore` method
21 * of the `@reduxjs/toolkit` package**, which replaces `createStore`.
22 *
23 * Redux Toolkit is our recommended approach for writing Redux logic today,
24 * including store setup, reducers, data fetching, and more.
25 *
26 * **For more details, please read this Redux docs page:**
27 * **https://redux.js.org/introduction/why-rtk-is-redux-today**
28 *
29 * `configureStore` from Redux Toolkit is an improved version of `createStore` that
30 * simplifies setup and helps avoid common bugs.
31 *
32 * You should not be using the `redux` core package by itself today, except for learning purposes.
33 * The `createStore` method from the core `redux` package will not be removed, but we encourage
34 * all users to migrate to using Redux Toolkit for all Redux code.
35 *
36 * If you want to use `createStore` without this visual deprecation warning, use
37 * the `legacy_createStore` import instead:
38 *
39 * `import { legacy_createStore as createStore} from 'redux'`
40 *
41 */
42export function createStore<
43 S,
44 A extends Action,
45 Ext extends {} = {},
46 StateExt extends {} = {}
47>(
48 reducer: Reducer<S, A>,
49 enhancer?: StoreEnhancer<Ext, StateExt>
50): Store<S, A, UnknownIfNonSpecific<StateExt>> & Ext
51/**
52 * @deprecated
53 *
54 * **We recommend using the `configureStore` method
55 * of the `@reduxjs/toolkit` package**, which replaces `createStore`.
56 *
57 * Redux Toolkit is our recommended approach for writing Redux logic today,
58 * including store setup, reducers, data fetching, and more.
59 *
60 * **For more details, please read this Redux docs page:**
61 * **https://redux.js.org/introduction/why-rtk-is-redux-today**
62 *
63 * `configureStore` from Redux Toolkit is an improved version of `createStore` that
64 * simplifies setup and helps avoid common bugs.
65 *
66 * You should not be using the `redux` core package by itself today, except for learning purposes.
67 * The `createStore` method from the core `redux` package will not be removed, but we encourage
68 * all users to migrate to using Redux Toolkit for all Redux code.
69 *
70 * If you want to use `createStore` without this visual deprecation warning, use
71 * the `legacy_createStore` import instead:
72 *
73 * `import { legacy_createStore as createStore} from 'redux'`
74 *
75 */
76export function createStore<
77 S,
78 A extends Action,
79 Ext extends {} = {},
80 StateExt extends {} = {},
81 PreloadedState = S
82>(
83 reducer: Reducer<S, A, PreloadedState>,
84 preloadedState?: PreloadedState | undefined,
85 enhancer?: StoreEnhancer<Ext, StateExt>
86): Store<S, A, UnknownIfNonSpecific<StateExt>> & Ext
87export function createStore<
88 S,
89 A extends Action,
90 Ext extends {} = {},
91 StateExt extends {} = {},
92 PreloadedState = S
93>(
94 reducer: Reducer<S, A, PreloadedState>,
95 preloadedState?: PreloadedState | StoreEnhancer<Ext, StateExt> | undefined,
96 enhancer?: StoreEnhancer<Ext, StateExt>
97): Store<S, A, UnknownIfNonSpecific<StateExt>> & Ext {
98 if (typeof reducer !== 'function') {
99 throw new Error(
100 `Expected the root reducer to be a function. Instead, received: '${kindOf(
101 reducer
102 )}'`
103 )
104 }
105
106 if (
107 (typeof preloadedState === 'function' && typeof enhancer === 'function') ||
108 (typeof enhancer === 'function' && typeof arguments[3] === 'function')
109 ) {
110 throw new Error(
111 'It looks like you are passing several store enhancers to ' +
112 'createStore(). This is not supported. Instead, compose them ' +
113 'together to a single function. See https://redux.js.org/tutorials/fundamentals/part-4-store#creating-a-store-with-enhancers for an example.'
114 )
115 }
116
117 if (typeof preloadedState === 'function' && typeof enhancer === 'undefined') {
118 enhancer = preloadedState as StoreEnhancer<Ext, StateExt>
119 preloadedState = undefined
120 }
121
122 if (typeof enhancer !== 'undefined') {
123 if (typeof enhancer !== 'function') {
124 throw new Error(
125 `Expected the enhancer to be a function. Instead, received: '${kindOf(
126 enhancer
127 )}'`
128 )
129 }
130
131 return enhancer(createStore)(
132 reducer,
133 preloadedState as PreloadedState | undefined
134 )
135 }
136
137 let currentReducer = reducer
138 let currentState: S | PreloadedState | undefined = preloadedState as
139 | PreloadedState
140 | undefined
141 let currentListeners: Map<number, ListenerCallback> | null = new Map()
142 let nextListeners = currentListeners
143 let listenerIdCounter = 0
144 let isDispatching = false
145
146 /**
147 * This makes a shallow copy of currentListeners so we can use
148 * nextListeners as a temporary list while dispatching.
149 *
150 * This prevents any bugs around consumers calling
151 * subscribe/unsubscribe in the middle of a dispatch.
152 */
153 function ensureCanMutateNextListeners() {
154 if (nextListeners === currentListeners) {
155 nextListeners = new Map()
156 currentListeners.forEach((listener, key) => {
157 nextListeners.set(key, listener)
158 })
159 }
160 }
161
162 /**
163 * Reads the state tree managed by the store.
164 *
165 * @returns The current state tree of your application.
166 */
167 function getState(): S {
168 if (isDispatching) {
169 throw new Error(
170 'You may not call store.getState() while the reducer is executing. ' +
171 'The reducer has already received the state as an argument. ' +
172 'Pass it down from the top reducer instead of reading it from the store.'
173 )
174 }
175
176 return currentState as S
177 }
178
179 /**
180 * Adds a change listener. It will be called any time an action is dispatched,
181 * and some part of the state tree may potentially have changed. You may then
182 * call `getState()` to read the current state tree inside the callback.
183 *
184 * You may call `dispatch()` from a change listener, with the following
185 * caveats:
186 *
187 * 1. The subscriptions are snapshotted just before every `dispatch()` call.
188 * If you subscribe or unsubscribe while the listeners are being invoked, this
189 * will not have any effect on the `dispatch()` that is currently in progress.
190 * However, the next `dispatch()` call, whether nested or not, will use a more
191 * recent snapshot of the subscription list.
192 *
193 * 2. The listener should not expect to see all state changes, as the state
194 * might have been updated multiple times during a nested `dispatch()` before
195 * the listener is called. It is, however, guaranteed that all subscribers
196 * registered before the `dispatch()` started will be called with the latest
197 * state by the time it exits.
198 *
199 * @param listener A callback to be invoked on every dispatch.
200 * @returns A function to remove this change listener.
201 */
202 function subscribe(listener: () => void) {
203 if (typeof listener !== 'function') {
204 throw new Error(
205 `Expected the listener to be a function. Instead, received: '${kindOf(
206 listener
207 )}'`
208 )
209 }
210
211 if (isDispatching) {
212 throw new Error(
213 'You may not call store.subscribe() while the reducer is executing. ' +
214 'If you would like to be notified after the store has been updated, subscribe from a ' +
215 'component and invoke store.getState() in the callback to access the latest state. ' +
216 'See https://redux.js.org/api/store#subscribelistener for more details.'
217 )
218 }
219
220 let isSubscribed = true
221
222 ensureCanMutateNextListeners()
223 const listenerId = listenerIdCounter++
224 nextListeners.set(listenerId, listener)
225
226 return function unsubscribe() {
227 if (!isSubscribed) {
228 return
229 }
230
231 if (isDispatching) {
232 throw new Error(
233 'You may not unsubscribe from a store listener while the reducer is executing. ' +
234 'See https://redux.js.org/api/store#subscribelistener for more details.'
235 )
236 }
237
238 isSubscribed = false
239
240 ensureCanMutateNextListeners()
241 nextListeners.delete(listenerId)
242 currentListeners = null
243 }
244 }
245
246 /**
247 * Dispatches an action. It is the only way to trigger a state change.
248 *
249 * The `reducer` function, used to create the store, will be called with the
250 * current state tree and the given `action`. Its return value will
251 * be considered the **next** state of the tree, and the change listeners
252 * will be notified.
253 *
254 * The base implementation only supports plain object actions. If you want to
255 * dispatch a Promise, an Observable, a thunk, or something else, you need to
256 * wrap your store creating function into the corresponding middleware. For
257 * example, see the documentation for the `redux-thunk` package. Even the
258 * middleware will eventually dispatch plain object actions using this method.
259 *
260 * @param action A plain object representing “what changed”. It is
261 * a good idea to keep actions serializable so you can record and replay user
262 * sessions, or use the time travelling `redux-devtools`. An action must have
263 * a `type` property which may not be `undefined`. It is a good idea to use
264 * string constants for action types.
265 *
266 * @returns For convenience, the same action object you dispatched.
267 *
268 * Note that, if you use a custom middleware, it may wrap `dispatch()` to
269 * return something else (for example, a Promise you can await).
270 */
271 function dispatch(action: A) {
272 if (!isPlainObject(action)) {
273 throw new Error(
274 `Actions must be plain objects. Instead, the actual type was: '${kindOf(
275 action
276 )}'. You may need to add middleware to your store setup to handle dispatching other values, such as 'redux-thunk' to handle dispatching functions. See https://redux.js.org/tutorials/fundamentals/part-4-store#middleware and https://redux.js.org/tutorials/fundamentals/part-6-async-logic#using-the-redux-thunk-middleware for examples.`
277 )
278 }
279
280 if (typeof action.type === 'undefined') {
281 throw new Error(
282 'Actions may not have an undefined "type" property. You may have misspelled an action type string constant.'
283 )
284 }
285
286 if (typeof action.type !== 'string') {
287 throw new Error(
288 `Action "type" property must be a string. Instead, the actual type was: '${kindOf(
289 action.type
290 )}'. Value was: '${action.type}' (stringified)`
291 )
292 }
293
294 if (isDispatching) {
295 throw new Error('Reducers may not dispatch actions.')
296 }
297
298 try {
299 isDispatching = true
300 currentState = currentReducer(currentState, action)
301 } finally {
302 isDispatching = false
303 }
304
305 const listeners = (currentListeners = nextListeners)
306 listeners.forEach(listener => {
307 listener()
308 })
309 return action
310 }
311
312 /**
313 * Replaces the reducer currently used by the store to calculate the state.
314 *
315 * You might need this if your app implements code splitting and you want to
316 * load some of the reducers dynamically. You might also need this if you
317 * implement a hot reloading mechanism for Redux.
318 *
319 * @param nextReducer The reducer for the store to use instead.
320 */
321 function replaceReducer(nextReducer: Reducer<S, A>): void {
322 if (typeof nextReducer !== 'function') {
323 throw new Error(
324 `Expected the nextReducer to be a function. Instead, received: '${kindOf(
325 nextReducer
326 )}`
327 )
328 }
329
330 currentReducer = nextReducer as unknown as Reducer<S, A, PreloadedState>
331
332 // This action has a similar effect to ActionTypes.INIT.
333 // Any reducers that existed in both the new and old rootReducer
334 // will receive the previous state. This effectively populates
335 // the new state tree with any relevant data from the old one.
336 dispatch({ type: ActionTypes.REPLACE } as A)
337 }
338
339 /**
340 * Interoperability point for observable/reactive libraries.
341 * @returns A minimal observable of state changes.
342 * For more information, see the observable proposal:
343 * https://github.com/tc39/proposal-observable
344 */
345 function observable() {
346 const outerSubscribe = subscribe
347 return {
348 /**
349 * The minimal observable subscription method.
350 * @param observer Any object that can be used as an observer.
351 * The observer object should have a `next` method.
352 * @returns An object with an `unsubscribe` method that can
353 * be used to unsubscribe the observable from the store, and prevent further
354 * emission of values from the observable.
355 */
356 subscribe(observer: unknown) {
357 if (typeof observer !== 'object' || observer === null) {
358 throw new TypeError(
359 `Expected the observer to be an object. Instead, received: '${kindOf(
360 observer
361 )}'`
362 )
363 }
364
365 function observeState() {
366 const observerAsObserver = observer as Observer<S>
367 if (observerAsObserver.next) {
368 observerAsObserver.next(getState())
369 }
370 }
371
372 observeState()
373 const unsubscribe = outerSubscribe(observeState)
374 return { unsubscribe }
375 },
376
377 [$$observable]() {
378 return this
379 }
380 }
381 }
382
383 // When a store is created, an "INIT" action is dispatched so that every
384 // reducer returns their initial state. This effectively populates
385 // the initial state tree.
386 dispatch({ type: ActionTypes.INIT } as A)
387
388 const store = {
389 dispatch: dispatch as Dispatch<A>,
390 subscribe,
391 getState,
392 replaceReducer,
393 [$$observable]: observable
394 } as unknown as Store<S, A, StateExt> & Ext
395 return store
396}
397
398/**
399 * Creates a Redux store that holds the state tree.
400 *
401 * **We recommend using `configureStore` from the
402 * `@reduxjs/toolkit` package**, which replaces `createStore`:
403 * **https://redux.js.org/introduction/why-rtk-is-redux-today**
404 *
405 * The only way to change the data in the store is to call `dispatch()` on it.
406 *
407 * There should only be a single store in your app. To specify how different
408 * parts of the state tree respond to actions, you may combine several reducers
409 * into a single reducer function by using `combineReducers`.
410 *
411 * @param {Function} reducer A function that returns the next state tree, given
412 * the current state tree and the action to handle.
413 *
414 * @param {any} [preloadedState] The initial state. You may optionally specify it
415 * to hydrate the state from the server in universal apps, or to restore a
416 * previously serialized user session.
417 * If you use `combineReducers` to produce the root reducer function, this must be
418 * an object with the same shape as `combineReducers` keys.
419 *
420 * @param {Function} [enhancer] The store enhancer. You may optionally specify it
421 * to enhance the store with third-party capabilities such as middleware,
422 * time travel, persistence, etc. The only store enhancer that ships with Redux
423 * is `applyMiddleware()`.
424 *
425 * @returns {Store} A Redux store that lets you read the state, dispatch actions
426 * and subscribe to changes.
427 */
428export function legacy_createStore<
429 S,
430 A extends Action,
431 Ext extends {} = {},
432 StateExt extends {} = {}
433>(
434 reducer: Reducer<S, A>,
435 enhancer?: StoreEnhancer<Ext, StateExt>
436): Store<S, A, UnknownIfNonSpecific<StateExt>> & Ext
437/**
438 * Creates a Redux store that holds the state tree.
439 *
440 * **We recommend using `configureStore` from the
441 * `@reduxjs/toolkit` package**, which replaces `createStore`:
442 * **https://redux.js.org/introduction/why-rtk-is-redux-today**
443 *
444 * The only way to change the data in the store is to call `dispatch()` on it.
445 *
446 * There should only be a single store in your app. To specify how different
447 * parts of the state tree respond to actions, you may combine several reducers
448 * into a single reducer function by using `combineReducers`.
449 *
450 * @param {Function} reducer A function that returns the next state tree, given
451 * the current state tree and the action to handle.
452 *
453 * @param {any} [preloadedState] The initial state. You may optionally specify it
454 * to hydrate the state from the server in universal apps, or to restore a
455 * previously serialized user session.
456 * If you use `combineReducers` to produce the root reducer function, this must be
457 * an object with the same shape as `combineReducers` keys.
458 *
459 * @param {Function} [enhancer] The store enhancer. You may optionally specify it
460 * to enhance the store with third-party capabilities such as middleware,
461 * time travel, persistence, etc. The only store enhancer that ships with Redux
462 * is `applyMiddleware()`.
463 *
464 * @returns {Store} A Redux store that lets you read the state, dispatch actions
465 * and subscribe to changes.
466 */
467export function legacy_createStore<
468 S,
469 A extends Action,
470 Ext extends {} = {},
471 StateExt extends {} = {},
472 PreloadedState = S
473>(
474 reducer: Reducer<S, A, PreloadedState>,
475 preloadedState?: PreloadedState | undefined,
476 enhancer?: StoreEnhancer<Ext, StateExt>
477): Store<S, A, UnknownIfNonSpecific<StateExt>> & Ext
478export function legacy_createStore<
479 S,
480 A extends Action,
481 Ext extends {} = {},
482 StateExt extends {} = {},
483 PreloadedState = S
484>(
485 reducer: Reducer<S, A>,
486 preloadedState?: PreloadedState | StoreEnhancer<Ext, StateExt> | undefined,
487 enhancer?: StoreEnhancer<Ext, StateExt>
488): Store<S, A, UnknownIfNonSpecific<StateExt>> & Ext {
489 return createStore(reducer, preloadedState as any, enhancer)
490}