All files / src connectStore.js

100% Statements 8/8
50% Branches 5/10
100% Functions 3/3
100% Lines 8/8

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59                                                            1x       6x   6x 6x       6x 12x     6x       1x                  
import { connect } from 'react-redux';
 
/**
 * Connects the state, selectors and dispatchers to components.
 * @example
 * import { connectStore } from "redux-box";
 * import { selectors, dispatchers } from "./store/userModule";
 *
 * connectStore({
 *  mapState: state => ({ name: state.user.name }),
 *  mapSelectors: { userProfile : getProfile },
 *  mapDispatchers: { getProfile: fetchProfile }
 * })
 *
 * @param {Object} connectParams - context object for connecting store to component
 * @param {Function} connectParams.mapState - maps store-state to component-props
 * @param {Object | Function} connectParams.mapDispatchers - maps module-dispatchers to component-props
 * @param {Object} connectParams.mapSelectors - maps module-selectors to component-props
 * @param {Function} connectParams.mergeProps - merges returned values from mapState, mapSelectors and mapDispatchers to return final component-props
 * @param {Object} connectParams.options - optional object passed to react-redux's connect function as fourth argument
 * @returns {Function} - return the output of connect() from react-redux
 */
 
function connectStore(connectParams = {}) {
  const {
    mapState = undefined,
    mapDispatchers = {},
    mapSelectors = {},
    mergeProps = undefined,
    options = undefined,
  } = connectParams;
 
  /* Map state and selectors to component-props */
  function mapStateToProps(state, props) {
    let finalProps = {};
 
    Eif (mapState && typeof mapState === 'function') {
      finalProps = { ...mapState(state, props) };
    }
 
    /* Call all selectors with  */
    Object.entries(mapSelectors).forEach(([propName, selector]) => {
      finalProps[propName] = selector.call(undefined, state, props);
    });
 
    return finalProps;
  }
 
  // connect
  return connect(
    mapStateToProps,
    mapDispatchers,
    mergeProps,
    options
  );
}
 
export default connectStore;