Yasir
Yasir

Reputation: 909

HOC as an App Wrapper for React Redux

I wanted to have an app HOC that wraps each component view. This HOC authenticates user and sets Google Analytics tracking. I'm upgrading to Router 4, and having an issue with making it work.

It's giving me the following error -

TypeError: (0 , _AppWrapper2.default) is not a function

Which is likely related to how I am creating the HOC. Any ideas?

routes.js

export default (
  <Switch>
    <Route exact path="/" component={AppWrapper(Home)} />
    <Route exact path="/channels" component={AppWrapper(Channels)} />
 </Switch>

);

const AppWrapper = (WrappedComponent) => {
  return class AppWrapperComponent extends Component {
    constructor(props) {
     super(props);
    }

    componentDidMount() {
      const page = this.props.location.pathname;
      this.trackPage(page);
    }

    componentWillReceiveProps(nextProps) {
      const currentPage = this.props.location.pathname;
      const nextPage = nextProps.location.pathname;

      if (currentPage !== nextPage) {
        this.trackPage(nextPage);
      }
    }

    trackPage = page => {
      GoogleAnalytics.set({
        page,
        ...options,
      });
      GoogleAnalytics.pageview(page);
    };

   render() {
     return (
      <div>
        {this.state.isMounted && !window.devToolsExtension && process.env.NODE_ENV === 'development' && <DevTools />}
        <WrappedComponent {...this.props.chidren} />
      </div>
     );
   }
 }

Upvotes: 0

Views: 451

Answers (1)

Oblosys
Oblosys

Reputation: 15106

Looks like you're not exporting AppWrapper. If you import it with import AppWrapper from .., add this line at the end of AppWrapper.js:

export default AppWrapper;

or replace the const declaration with

export default (WrappedComponent) => { ..

If you import it with import {AppWrapper} from .., you can insert an export before the const:

export const AppWrapper = (WrappedComponent) => {

Upvotes: 1

Related Questions