5

I am using the recompose library and HoCs to pass down a bunch of props for my component. I'd like to know if there is a way, within the compose to check for props before setting up an HoC. For example, say I have something like this:

export default compose(
  withProps(props => ({
    shouldUseWithMyHoc: someCondition() // true or false
  })),
  withState('someState', 'setSomeState', ''),
  withHandlers({
    doStuff: props => evt => {
      // do stuff
    }
  }),
  withMyHoc() // should only use if `shouldUseWithMyHoc` prop is true
)(MyComponent)

What can I do so that withMyHoc is only used when shouldUseWithMyHoc is set to true?

I thought of perhaps doing a ternary, but that didn't go well and I had nothing to fallback on when the condition was false. It looked something like this:

  export default compose (
  ...
  (props) => {(
    props.shouldUseWithMyHoc
    ? withMyHoc()
    : null)}
  )(MyComponent)

By using the ternary, I get the following error:

Warning: Can't call setState (or forceUpdate) on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.

Is there a way I can get this done? If this seems correct, then what am I doing wrong?

theJuls
  • 6,788
  • 14
  • 73
  • 160
  • It's the only way you can get it. About error, can you post your `MyComponent`? – The Reason Jul 12 '18 at 19:26
  • Thanks for your help. It turns out that I can do it using the `branch` HoC. I don't know why that original error was happening, but branch solved it. – theJuls Jul 12 '18 at 20:10

1 Answers1

4

Turns out I just needed to better word my question on google. The branch HoC from recompose solved my problem, as specified here

For my component, by the time I finished applying branch, this is what it looked like:

export default compose(
  withProps(props => ({
    shouldUseWithMyHoc: someCondition() // true or false
  })),
  withState('someState', 'setSomeState', ''),
  withHandlers({
    doStuff: props => evt => {
      // do stuff
    }
  }),
  branch(
    (props) => props.shouldUseWithMyHoc,
    withMyHoc()
  )
)(MyComponent)
theJuls
  • 6,788
  • 14
  • 73
  • 160