MCPcopy
hub / github.com/reduxjs/redux / subscribe

Function subscribe

src/createStore.ts:202–244  ·  src/createStore.ts::subscribe

* Adds a change listener. It will be called any time an action is dispatched, * and some part of the state tree may potentially have changed. You may then * call `getState()` to read the current state tree inside the callback. * * You may call `dispatch()` from a change listener, with th

(listener: () => void)

Source from the content-addressed store, hash-verified

200 * @returns A function to remove this change listener.
201 */
202 function subscribe(listener: () => void) {
203 if (typeof listener !== class="st">'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 class="st">'You may not call store.subscribe() while the reducer is executing. ' +
214 class="st">'If you would like to be notified after the store has been updated, subscribe from a ' +
215 class="st">'component and invoke store.getState() in the callback to access the latest state. ' +
216 class="st">'See https:class="cm">//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 class="st">'You may not unsubscribe from a store listener while the reducer is executing. ' +
234 class="st">'See https:class="cm">//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.

Callers

nothing calls this directly

Calls 3

kindOfFunction · 0.90
observeStateFunction · 0.85

Tested by

no test coverage detected