All files / packages/react-tao/src DataConsumer.js

13.33% Statements 2/15
0% Branches 0/6
0% Functions 0/4
13.33% Lines 2/15
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                                                                                  2x   2x                              
import React, { Component } from 'react';
import PropTypes from 'prop-types';
 
import { Context } from './Provider';
 
function recursiveContextGenerator(
  ctxList,
  getContext,
  children,
  ctxIdx = 0,
  ctxDataArgs = []
) {
  const ctxName = ctxList[ctxIdx];
  const context = getContext(ctxName);
  if (ctxList.length > ctxIdx + 1) {
    return (
      <context.Consumer name={`${ctxName}.Consumer`}>
        {ctxData => {
          ctxDataArgs.push(ctxData);
          return recursiveContextGenerator(
            ctxList,
            getContext,
            children,
            ctxIdx + 1,
            ctxDataArgs
          );
        }}
      </context.Consumer>
    );
  }
  return (
    <context.Consumer name={`${ctxName}.Consumer`}>
      {ctxData => {
        ctxDataArgs.push(ctxData);
        return children(...ctxDataArgs);
      }}
    </context.Consumer>
  );
}
 
export default class DataConsumer extends Component {
  static contextType = Context;
 
  static propTypes = {
    context: PropTypes.oneOfType([
      PropTypes.string,
      PropTypes.arrayOf(PropTypes.string)
    ]).isRequired,
    children: PropTypes.func.isRequired
  };
 
  render() {
    const { context, children } = this.props;
    const { getDataContext } = this.context;
    const ctxList = Array.isArray(context) ? context : [context];
    return recursiveContextGenerator(ctxList, getDataContext, children);
  }
}