source: imaps-frontend/node_modules/react-use/lib/factory/createReducer.js@ d565449

main
Last change on this file since d565449 was d565449, checked in by stefan toskovski <stefantoska84@…>, 4 weeks ago

Update repo after prototype presentation

  • Property mode set to 100644
File size: 2.1 KB
Line 
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3var tslib_1 = require("tslib");
4var react_1 = require("react");
5var useUpdateEffect_1 = tslib_1.__importDefault(require("../useUpdateEffect"));
6function composeMiddleware(chain) {
7 return function (context, dispatch) {
8 return chain.reduceRight(function (res, middleware) {
9 return middleware(context)(res);
10 }, dispatch);
11 };
12}
13var createReducer = function () {
14 var middlewares = [];
15 for (var _i = 0; _i < arguments.length; _i++) {
16 middlewares[_i] = arguments[_i];
17 }
18 var composedMiddleware = composeMiddleware(middlewares);
19 return function (reducer, initialState, initializer) {
20 if (initializer === void 0) { initializer = function (value) { return value; }; }
21 var ref = react_1.useRef(initializer(initialState));
22 var _a = react_1.useState(ref.current), setState = _a[1];
23 var dispatch = react_1.useCallback(function (action) {
24 ref.current = reducer(ref.current, action);
25 setState(ref.current);
26 return action;
27 }, [reducer]);
28 var dispatchRef = react_1.useRef(composedMiddleware({
29 getState: function () { return ref.current; },
30 dispatch: function () {
31 var args = [];
32 for (var _i = 0; _i < arguments.length; _i++) {
33 args[_i] = arguments[_i];
34 }
35 return dispatchRef.current.apply(dispatchRef, args);
36 },
37 }, dispatch));
38 useUpdateEffect_1.default(function () {
39 dispatchRef.current = composedMiddleware({
40 getState: function () { return ref.current; },
41 dispatch: function () {
42 var args = [];
43 for (var _i = 0; _i < arguments.length; _i++) {
44 args[_i] = arguments[_i];
45 }
46 return dispatchRef.current.apply(dispatchRef, args);
47 },
48 }, dispatch);
49 }, [dispatch]);
50 return [ref.current, dispatchRef.current];
51 };
52};
53exports.default = createReducer;
Note: See TracBrowser for help on using the repository browser.