1
votes

I want to create a HOC that would allow me to call methods which will fetch data from backend and display a loader mask if they're loading. The trick is that I want to be able to pass different actions for different components.

So I'd like to call it like that:

export default withPage({
  getLoadingStatus: getStatus,
  actionOnLoad: booksActions.getAllBooksRequest
})(ShareABookContainer);

As I'm passing some props there I defined my withPage.js like below:

const withPage = ({
  actionOnLoad,
  getLoadingStatus
}) => WrappedComponent => () => {
  return (
    <PageContainer
      getLoadingStatus={getLoadingStatus}
      wrappedComponent={WrappedComponent}
      actionOnLoad={actionOnLoad}
    />
  );
};

export default withPage;

PageContainer.js is the most common container, so:

const PageContainer = props => <PageComponent {...props} />;


const mapStateToProps = (state, ownProps) => ({
  ...
});

const mapDispatchToProps = (dispatch, ownProps) => {
...
};

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(PageContainer);

And PageComponent is a common Component as well:

class PageComponent extends Component {
  componentDidMount() {
   ...
  }

  render() { return <this.props.wrappedComponent />;
  }
}

export default PageComponent;

What happens is that nothing gets rendered and if I console.log wrappedComponent I receive:

WrappedComponent ƒ a(e,t){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,a);var r=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super()…

When I'm passing some div, e.g. test instead of everything works fine, but what I need is for passed component to be rendered.

I have no idea what I'm doing wrong and examples in the Internet are not helping either. I wasn't able to find an example for a situation like mine (so passing props to HOC and using Redux there, it's either one or the other). I'd be very grateful for any thoughts/suggestions/answers.

1
I'm not sure, but I think your hoc definition should look more like that: const withPage = ({ actionOnLoad, getLoadingStatus }) => WrappedComponent => <SomeComponent/> So without this last empty arrow function.Maciej Wojsław
@MaciejWojsław thank you for your suggestion but it doesn't work. Without the last empty arrow function I get Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. weronika wlochh

1 Answers

0
votes

Try simpler:

return (
  <PageContainer
    getLoadingStatus={getLoadingStatus}
    actionOnLoad={actionOnLoad} >
    <WrappedComponent />
  </PageContainer>
);

BTW, react rather 'doesn't like' <this.props.wrappedComponent /> No errors??

When needed dynamic components I probably used sth like:

const Wrapped = this.props.wrappedComponent;
render () { return <Wrapped /> }

Var name had to be uppercased.