Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use currying to create HoC in React and connect to the Redux store at the same time?

I'm using React and Redux with react-redux, and I'm creating in React a High order Component that I want to connect to the Redux store, like this:

const HoC = parameter => WrappedComponent => 
    return class WithSelected extends Component {

    // ..some use of 'parameter'

    render() { 

         return <WrappedComponent />

     }

  [...]

  const exportComponent = compose(
      connect(mapStateToProps),
      HoC
   )

 export default exportComponent;

and

import Component from '../Component'
import exportComponent from '../file'

const componentToExport = exportComponent('someValue')(Component);

Now, this approach gives this error:

TypeError: Object(...) is not a function

Btw if I don't use currying creating the Hoc, it works, like this:

const HoC = (parameter, WrappedComponent)  => [etc]

and

import Component from '../Component'
import exportComponent from '../file'

const componentToExport = exportComponent('someValue', Component);

It works. But how can I use currying creating HoC in React and use Redux at the same time?

like image 240
AmintaCode Avatar asked Nov 20 '19 18:11

AmintaCode


1 Answers

There is nothing wrong with currying an HOC. The following is a valid high order component

const withHoc = param => Component => props =>{
  return <Component {...props} foo={param} />
}

Your problem is compose. Your right-most argument which will provide the signature for the resulting composed function is actually evaluating to another HOC not the component itself.


You should connect the returned component

const HoC = parameter => WrappedComponent => connect(...)(props =>{
    /*...*/
})

Returning a class based component is the same as returning a functional one

const HoC = parameter => WrappedComponent => connect(...)(class X extends Component{
    render(){ return <div /> }
})

Just isn't that pretty though

like image 59
Dupocas Avatar answered Oct 19 '22 09:10

Dupocas