Skip to content

Commit f05e3c6

Browse files
authored
Freeze initial state by passing through Immer (#940)
* Freeze initial state by passing through Immer * Fix unused parameter error
1 parent 194d019 commit f05e3c6

File tree

2 files changed

+13
-1
lines changed

2 files changed

+13
-1
lines changed

src/createReducer.test.ts

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,16 @@ describe('createReducer', () => {
9090
'Cannot add property text, object is not extensible'
9191
)
9292
})
93+
94+
test('Freezes initial state', () => {
95+
const initialState = [{ text: 'Buy milk' }]
96+
const todosReducer = createReducer(initialState, {})
97+
98+
const mutateStateOutsideReducer = () => (initialState[0].text = 'edited')
99+
expect(mutateStateOutsideReducer).toThrowError(
100+
/Cannot assign to read only property/
101+
)
102+
})
93103
})
94104

95105
describe('given pure reducers with immutable updates', () => {

src/createReducer.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -199,7 +199,9 @@ export function createReducer<S>(
199199
? executeReducerBuilderCallback(mapOrBuilderCallback)
200200
: [mapOrBuilderCallback, actionMatchers, defaultCaseReducer]
201201

202-
return function(state = initialState, action): S {
202+
const frozenInitialState = createNextState(initialState, () => {})
203+
204+
return function(state = frozenInitialState, action): S {
203205
let caseReducers = [
204206
actionsMap[action.type],
205207
...finalActionMatchers

0 commit comments

Comments
 (0)