Search code examples
reactjsreduxpolling

Use redux connect function passing props.children as React element


I need a component that starts polling for data from an API as soon as it gets mounted and it stops when unmounted. The data must be available for a child component.

This is my current implementation skeleton

class External extends Component {
  render() {
    const ConnectedPoller = connect(/*cut*/)(Poller)

    return <ConnectedPoller {...this.props}>
      {this.props.children}
    </ConnectedPoller>
  }
}

class Poller extends Component {
  componentDidMount() {
    this.model.startPolling();
  }

  componentWillUnmount() {
    this.model.stopPolling();
  }

  render() {
    const children = React.Children.map(this.props.children, child => {
      return React.cloneElement(child, {...this.props});
    });

    return children;
  }
}

There are a few components that need these data, I can use my poller as their parent in this way

<External>
  <ComponentRequiringData {...this.props}>
</External>

This is working, but I would like to merge External into Poller. The problem is that I cannot find a way to do this

const ConnectedPoller = connect(/*cut*/)(this.props.children)

The connect function complains when I pass props.children instead of a "real" react element. Any suggestion?

DISCLAIMER: I don't poll at an ancestor level because it's a heavy resource-consuming task for the backend and I need those data only in a few components that are used rarely and are never rendered together in the same page.


Solution

  • The only reason to use redux' connect function, is if you want to connect to the state manangement - either get the current state, or dispatch an action. Since you aren't doing any of these here, there is no reason to use connect. Also, while it might work, there is no reason to use connect inside a rendering function. This will recreate the commponent over and over again for no reason. I guess you are doing it because you want to pass the component with props, but connect can receive props from a parent element as a second argument.