UNPKG

react-redux-methods

Version:

A lightweight react-redux toolkit for writing strong-typed, minimal code redux boilerplate.

59 lines (58 loc) 2.66 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.createConnector = void 0; var react_redux_1 = require("react-redux"); var mapStateConnector = function (selectors, mapState) { if (!mapState) return undefined; var selectedState = mapState(selectors); return function (state) { var result = {}; for (var key in selectedState) { if (selectedState[key]) { result[key] = selectedState[key](state); } } return result; }; }; var mapDispatchConnector = function (actions, mapDispatch) { return mapDispatch ? mapDispatch(actions) : undefined; }; /** * A utility function which simplifies redux's 'connect' boilerplate specifically when providing 'mapStateToProps' and/or 'mapDispatchToProps' * parameters. This function extends typescript intelliSense for passing props to react component. * * @param mapState A callback function that accepts a single parameter 'selectors' and returns an object of the selected * case reducer states or what we call 'mapStateToProps'. The parameter contains all use case selections provided during the creation of each case reducer ( * see 'createReduxMethods' function for more reference). * @param mapDispatch Same to mapState, mapDispatch is a callback function with a single parameter-'actions' and returns an object * called 'mapDispatchToProps'. This parameter provides the list of all available actions within redux context. * @returns a function returned from react-redux's 'connect'. * * EXAMPLE: * const connector = reduxConnector( * (s) => ({ * savedSearchMutation: s.getSavedSearchMutation, * accountingPeriodEntrySkipFetch: s.getAccountingPeriodEntrySkipFetch, * currentUser: s.getCurrentUser, * }), * (a) => ({ openIsExport: a.openIsExport }) * ); */ var createConnector = function (selectors, actions) { return function connectWithMapFns(mapState, mapDispatch) { var stateToProps = mapStateConnector(selectors, mapState); var dispatchToProps = mapDispatchConnector(actions, mapDispatch); var connector = (0, react_redux_1.connect)(stateToProps, dispatchToProps); return connector; }; }; exports.createConnector = createConnector; // export const createConnector = <S, A>(selectors: S, actions: A): IReduxConnectorFn<S, A> => { // return (mapState: any, mapDispatch: any) => { // const mapStateToProps = mapStateConnector(selectors, mapState); // const mapDispatchToProps = mapDispatchConnector(actions, mapDispatch); // return connect(mapStateToProps, mapDispatchToProps); // }; // };