All files connectRealm.js

75% Statements 12/16
100% Branches 6/6
66.67% Functions 6/9
75% Lines 12/16
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 60 61 62 63              2x                   5x   5x 5x   5x                             3x 1x           2x       1x       1x       5x   5x        
import PropTypes from 'prop-types';
import React from 'react';
import pluralize from 'pluralize';
import camelcase from 'camelcase';
import hoistNonReactStatic from 'hoist-non-react-statics';
 
export function getResultsName(schema) {
  return pluralize(camelcase(schema), 2);
}
 
function connectRealm(WrappedComponent, options) {
  class ConnectedRealmComponent extends React.Component {
    static contextTypes = {
      reactRealmInstance: PropTypes.object,
    };
 
    constructor(props, context) {
      super(props, context);
 
      this.schemaList = options.schemas || [];
      this.results = {};
 
      this.schemaList.forEach(schema => {
        this.results[
          getResultsName(schema)
        ] = context.reactRealmInstance.objects(schema);
        this.results[getResultsName(schema)].addListener(this.updateView);
      });
    }
 
    componentWillUnmount() {
      this.schemaList.forEach(schema => {
        this.results[getResultsName(schema)].removeListener(this.updateView);
      });
    }
 
    getProps = () => {
      if (options && typeof options.mapToProps === 'function') {
        return options.mapToProps(
          this.results,
          this.context.reactRealmInstance,
          this.props,
        );
      }
      return {};
    };
 
    updateView = () => {
      this.forceUpdate();
    };
 
    render() {
      return <WrappedComponent {...this.getProps()} {...this.props} />;
    }
  }
 
  hoistNonReactStatic(ConnectedRealmComponent, WrappedComponent);
 
  return ConnectedRealmComponent;
}
 
export default connectRealm;