1 | "use strict";
|
---|
2 | Object.defineProperty(exports, "__esModule", { value: true });
|
---|
3 | var tslib_1 = require("tslib");
|
---|
4 | var react_1 = require("react");
|
---|
5 | var useUpdateEffect_1 = tslib_1.__importDefault(require("../useUpdateEffect"));
|
---|
6 | function composeMiddleware(chain) {
|
---|
7 | return function (context, dispatch) {
|
---|
8 | return chain.reduceRight(function (res, middleware) {
|
---|
9 | return middleware(context)(res);
|
---|
10 | }, dispatch);
|
---|
11 | };
|
---|
12 | }
|
---|
13 | var 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 | };
|
---|
53 | exports.default = createReducer;
|
---|