Skip to content

Commit

Permalink
Freeze initial state by passing through Immer (#940)
Browse files Browse the repository at this point in the history
* Freeze initial state by passing through Immer

* Fix unused parameter error
  • Loading branch information
markerikson authored Mar 25, 2021
1 parent 194d019 commit f05e3c6
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 1 deletion.
10 changes: 10 additions & 0 deletions src/createReducer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,16 @@ describe('createReducer', () => {
'Cannot add property text, object is not extensible'
)
})

test('Freezes initial state', () => {
const initialState = [{ text: 'Buy milk' }]
const todosReducer = createReducer(initialState, {})

const mutateStateOutsideReducer = () => (initialState[0].text = 'edited')
expect(mutateStateOutsideReducer).toThrowError(
/Cannot assign to read only property/
)
})
})

describe('given pure reducers with immutable updates', () => {
Expand Down
4 changes: 3 additions & 1 deletion src/createReducer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -199,7 +199,9 @@ export function createReducer<S>(
? executeReducerBuilderCallback(mapOrBuilderCallback)
: [mapOrBuilderCallback, actionMatchers, defaultCaseReducer]

return function(state = initialState, action): S {
const frozenInitialState = createNextState(initialState, () => {})

return function(state = frozenInitialState, action): S {
let caseReducers = [
actionsMap[action.type],
...finalActionMatchers
Expand Down

0 comments on commit f05e3c6

Please sign in to comment.