Skip to content

createReducer with optional slice parameter #45

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions src/createReducer.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import createNextState from 'immer'

export function createReducer(initialState, actionsMap) {
return function(state = initialState, action) {
export function createReducer(initialState, actionsMap, slice = '') {
const reducer = function(state = initialState, action) {
return createNextState(state, draft => {
const caseReducer = actionsMap[action.type]

Expand All @@ -12,4 +12,9 @@ export function createReducer(initialState, actionsMap) {
return draft
})
}
if (typeof slice !== 'string') {
slice = ''
}
reducer.toString = () => slice
return reducer
}
11 changes: 11 additions & 0 deletions src/createReducer.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,17 @@ describe('createReducer', () => {

behavesLikeReducer(todosReducer)
})

describe('given a slice, reducer.toString()', () => {
it('should return the slice', () => {
const reducer = createReducer([], {}, 'todo')
expect(String(reducer)).toBe('todo')
})
it('should return an empty string when provided slice is empty or not a string', () => {
const reducer = createReducer([], {})
expect(String(reducer)).toBe('')
})
})
})

function behavesLikeReducer(todosReducer) {
Expand Down
2 changes: 1 addition & 1 deletion src/createSlice.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export function createSlice({ slice = '', reducers = {}, initialState }) {
return map
}, {})

const reducer = createReducer(initialState, reducerMap)
const reducer = createReducer(initialState, reducerMap, slice)

const actionMap = actionKeys.reduce((map, action) => {
const type = getType(slice, action)
Expand Down
4 changes: 4 additions & 0 deletions src/createSlice.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,10 @@ describe('createSlice', () => {
expect(reducer(undefined, actions.increment())).toEqual(1)
})

it('should return the correct type of the reducer', () => {
expect(String(reducer)).toEqual('cool')
})

it('should create selector with correct name', () => {
expect(selectors.hasOwnProperty('getCool')).toBe(true)
})
Expand Down