Created
November 9, 2020 11:31
-
-
Save hanipcode/627997e15c6ce2e6aaae3fc30de8366d to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import p from 'immer'; | |
interface CreateSliceOption { | |
name: string; | |
initialState: Record<string, unknown>; | |
reducers: Record<string, Function>; | |
} | |
const createKey = (name, key) => `${name}-reducer-${key}-action`; | |
function createSlice(option: CreateSliceOption) { | |
const { initialState, reducers, name } = option; | |
const actions: Record<keyof typeof reducers, Function> = {}; | |
const keyToActionsMap: Record<string, string> = {} | |
const reducersKey = Object.keys(reducers); | |
reducersKey.forEach(key => { | |
const keyName = createKey(name, key); | |
keyToActionsMap[keyName] = key; | |
actions[key] = payload => ({ | |
type: keyName, | |
payload, | |
}); | |
}); | |
const reducerFn = (state = initialState, action: any) => { | |
return p(state, draft => { | |
const keyName = createKey(name, action.type); | |
const selectedActions = reducers[keyToActionsMap[keyName]]; | |
selectedActions(state, action); | |
}); | |
}; | |
return { | |
reducer: reducerFn, | |
actions: (actions as Record<keyof typeof reducers, Function>), | |
}; | |
} | |
export default createSlice; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment