reactjsreact-hooksreact-hoc

TypeError: Object(...) is not a function when doing compose on ReactJS HOC


I have a component where I try to compose (imported from "compose-function" library) as below;

export function MyRoute() {
  let MyGridWithData = compose(
    withRouter,
    withTranslation("translations"),
    withMyApi()
  )(MyGrid);
  return <MyGridWithData />;
}

However, for some reason, I am seeing the below error;

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

The error is pointed on the line ; let MyGridWithData = compose(...)

Also, while withRouter & withTranslation are standard hooks, withMyApi is defined as below (it is a HOF basically);

export function withMyApi() {
  // Extra function wrapper 
  return function(WrappedComponent) {
    class MyApiUrls extends React.Component {
      constructor(props) {
        super(props);
      }

      render() {
        return <WrappedComponent api={this.api} {...this.props} />;
      }
    }
    return MyApiUrls;
  };
}

Solution

  • All looks correct except; probably you are incorrectly importing compose function.

    It is a default export, not a named one. So, the correct way to import is:

    import compose from 'compose-function';
    

    Side note: Don’t Use HOCs Inside the render Method as it similar to re-creating a component at every re-render. So, You should write it as:

    const MyGridWithData = compose(
        withRouter,
        withTranslation("translations"),
        withMyApi()
      )(MyGrid);
    
    export function MyRoute() {
      // more code if any
      return <MyGridWithData />;
    }