Skip to content

Instantly share code, notes, and snippets.

@hanipcode
Created November 9, 2020 11:31
Show Gist options
  • Save hanipcode/627997e15c6ce2e6aaae3fc30de8366d to your computer and use it in GitHub Desktop.
Save hanipcode/627997e15c6ce2e6aaae3fc30de8366d to your computer and use it in GitHub Desktop.
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