IAspireToBeGladOS
IAspireToBeGladOS

Reputation: 1484

ReactJS & MobX: TypeError: ... is not a function - but it is?

SidenavStore.js - defines if the Sidenav should be visible or not, default true:

const SidenavStore = types
  .model('SidenavStore', {
    isSidenavVisible: types.optional(types.boolean, true),
  })
  .actions(self => ({    
    hideSidenav: () => { self.isSidenavVisible = false; },
    showSidenav: () => { self.isSidenavVisible = true; },
  }));

export default SidenavStore;

The ErrorPage makes use of the SidenavStore to determine whether or not to show the Sidenav.

import sidenavStore from '../../../stores/SidenavStore';

class ErrorPage extends React.Component {
  componentDidMount() {
    sidenavStore.hideSidenav();
  }

  componentWillUnmount() {
    sidenavStore.showSidenav();
  }

  render() {
    return (
      <div>
        <h1>My Content Here</h1>
      </div>
    );
  }
}

And in App.jsx, the applicable code:

const sidebarStore = SidebarStore.create();

const App = () => (
  <BrowserRouter>
    <Provider sidebarStore={SidebarStore}>
      <Main>
        {code here}
      </Main>
    </Provider>
  </BrowserRouter>
);

export default App;

So my question is this:

In the browser, I'm getting the error TypeError: _stores_SidenavStore__WEBPACK_IMPORTED_MODULE_8__.default.hideSidenav is not a function. Yet, you can see that both hideSidenav and showSidenav exist in SidenavStore.js.

What am I referencing or doing wrong? Any guidance would be much appreciated.

Upvotes: 5

Views: 6723

Answers (1)

Tholle
Tholle

Reputation: 112807

You are currently importing the model and trying to use that. You instead want to get the instance from your Provider with inject and use that from the props.

import { observer, inject } from "mobx-react";

class ErrorPage extends React.Component {
  componentDidMount() {
    this.props.sidenavStore.hideSidenav();
  }

  componentWillUnmount() {
    this.props.sidenavStore.showSidenav();
  }

  render() {
    return (
      <div>
        <h1>My Content Here</h1>
      </div>
    );
  }
}

export default inject("sidebarStore")(observer(ErrorPage));

Upvotes: 5

Related Questions