UNPKG

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