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

Function stateExtension

test/typescript/enhancers.ts:49–92  ·  test/typescript/enhancers.ts::stateExtension

* Store enhancer that extends the type of the state.

()

Source from the content-addressed store, hash-verified

47 * Store enhancer that extends the type of the state.
48 */
49function stateExtension() {
50 interface ExtraState {
51 extraField: string
52 }
53
54 const enhancer: StoreEnhancer<{}, ExtraState> =
55 createStore =>
56 <S, A extends Action, PreloadedState>(
57 reducer: Reducer<S, A, PreloadedState>,
58 preloadedState?: PreloadedState | undefined
59 ) => {
60 function wrapReducer<PreloadedStateToWrap>(
61 reducer: Reducer<S, A, PreloadedStateToWrap>
62 ): Reducer<S & ExtraState, A, PreloadedStateToWrap & ExtraState> {
63 return (state, action) => {
64 const newState = reducer(state, action)
65 return {
66 ...newState,
67 extraField: class="st">'extra'
68 }
69 }
70 }
71 const wrappedPreloadedState = preloadedState
72 ? {
73 ...preloadedState,
74 extraField: class="st">'extra'
75 }
76 : undefined
77 const store = createStore(wrapReducer(reducer), wrappedPreloadedState)
78 return {
79 ...store,
80 replaceReducer(nextReducer: Reducer<S, A>) {
81 store.replaceReducer(wrapReducer(nextReducer))
82 }
83 }
84 }
85
86 const store = createStore(reducer, enhancer)
87
88 store.getState().someField
89 store.getState().extraField
90 class="cm">// @ts-expect-error
91 store.getState().wrongField
92}
93
94/**
95 * Store enhancer that adds methods to the store.

Callers

nothing calls this directly

Calls 2

createStoreFunction · 0.85
getStateMethod · 0.65

Tested by

no test coverage detected