source: imaps-frontend/node_modules/react-use/esm/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.0 KB
Line 
1import { useCallback, useRef, useState } from 'react';
2import useUpdateEffect from '../useUpdateEffect';
3function composeMiddleware(chain) {
4 return function (context, dispatch) {
5 return chain.reduceRight(function (res, middleware) {
6 return middleware(context)(res);
7 }, dispatch);
8 };
9}
10var 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};
50export default createReducer;
Note: See TracBrowser for help on using the repository browser.