react-micro-reducer
Version:
A React reducer hook, with a "micro"-reducer style, made for a Typescript world 💙
35 lines (34 loc) • 1.26 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
var react_1 = require("react");
// introduced generic R to allow proper infering
function useMicroReducer(microReducer, initialState, producer) {
var _a = react_1.useReducer(function (state, action) {
var _a;
if (producer) {
return producer(state, function (draft) {
var _a;
return (_a = microReducer(draft))[action.type].apply(_a, action.payload);
});
}
return (_a = microReducer(state))[action.type].apply(_a, action.payload);
}, initialState), state = _a[0], _dispatch = _a[1];
var dispatch = react_1.useMemo(function () {
var dispatch = {};
var _loop_1 = function (key) {
dispatch[key] = function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return _dispatch({ type: key, payload: args });
};
};
for (var key in microReducer()) {
_loop_1(key);
}
return dispatch;
}, [_dispatch]);
return [state, dispatch];
}
exports.useMicroReducer = useMicroReducer;
;