1 | import { useCallback, useRef, useState } from 'react';
|
---|
2 | import useUpdateEffect from '../useUpdateEffect';
|
---|
3 | function composeMiddleware(chain) {
|
---|
4 | return function (context, dispatch) {
|
---|
5 | return chain.reduceRight(function (res, middleware) {
|
---|
6 | return middleware(context)(res);
|
---|
7 | }, dispatch);
|
---|
8 | };
|
---|
9 | }
|
---|
10 | var createReducer = function () {
|
---|
11 | var middlewares = [];
|
---|
12 | for (var _i = 0; _i < arguments.length; _i++) {
|
---|
13 | middlewares[_i] = arguments[_i];
|
---|
14 | }
|
---|
15 | var composedMiddleware = composeMiddleware(middlewares);
|
---|
16 | return function (reducer, initialState, initializer) {
|
---|
17 | if (initializer === void 0) { initializer = function (value) { return value; }; }
|
---|
18 | var ref = useRef(initializer(initialState));
|
---|
19 | var _a = useState(ref.current), setState = _a[1];
|
---|
20 | var dispatch = useCallback(function (action) {
|
---|
21 | ref.current = reducer(ref.current, action);
|
---|
22 | setState(ref.current);
|
---|
23 | return action;
|
---|
24 | }, [reducer]);
|
---|
25 | var dispatchRef = useRef(composedMiddleware({
|
---|
26 | getState: function () { return ref.current; },
|
---|
27 | dispatch: function () {
|
---|
28 | var args = [];
|
---|
29 | for (var _i = 0; _i < arguments.length; _i++) {
|
---|
30 | args[_i] = arguments[_i];
|
---|
31 | }
|
---|
32 | return dispatchRef.current.apply(dispatchRef, args);
|
---|
33 | },
|
---|
34 | }, dispatch));
|
---|
35 | useUpdateEffect(function () {
|
---|
36 | dispatchRef.current = composedMiddleware({
|
---|
37 | getState: function () { return ref.current; },
|
---|
38 | dispatch: function () {
|
---|
39 | var args = [];
|
---|
40 | for (var _i = 0; _i < arguments.length; _i++) {
|
---|
41 | args[_i] = arguments[_i];
|
---|
42 | }
|
---|
43 | return dispatchRef.current.apply(dispatchRef, args);
|
---|
44 | },
|
---|
45 | }, dispatch);
|
---|
46 | }, [dispatch]);
|
---|
47 | return [ref.current, dispatchRef.current];
|
---|
48 | };
|
---|
49 | };
|
---|
50 | export default createReducer;
|
---|