UNPKG

@ffsm/store

Version:

A powerful state management library for React, providing a simple and efficient way to manage application state with built-in support for serialization, deserialization, and type safety.

40 lines (39 loc) 1.44 kB
/* eslint-disable @typescript-eslint/no-empty-object-type */ import { cloneDeep } from '@ffsm/utils/clone-deep'; import { mergeObject } from '@ffsm/utils/merge-object'; function getType(name, reducerName) { return "".concat(name, "/").concat(reducerName); } export function createSlice(options) { var name = options.name, initialState = options.initialState, reducers = options.reducers; var reducerNames = Object.keys(reducers); var types = mergeObject.apply(void 0, reducerNames.map(function (reducerName) { var _a; return (_a = {}, _a[getType(name, reducerName)] = reducerName, _a); })); function reducer(state, action) { if (state === void 0) { state = initialState; } var type = types[action.type]; var nextState = cloneDeep(state); if (reducers[type]) { var result = reducers[type](nextState, action); return cloneDeep(result !== null && result !== void 0 ? result : nextState); } return nextState; } var actions = mergeObject.apply(void 0, reducerNames.map(function (reducerName) { var _a; return (_a = {}, _a[reducerName] = function (payload) { return ({ type: getType(name, reducerName), payload: payload, }); }, _a); })); return { actions: actions, reducer: reducer, }; }