arxoft
arxoft

Reputation: 1475

Can't use custom class in React JS

I want to use a custom service in my project. I create a class, Ex: Services/Auth.js with following content.

class Auth {
    isLoggedIn() {
        return true;
    }
}

export default Auth;

Then in my component I import and use as under:

import Auth from './Services/Auth';
class App extends Component {
    render() {
        const isLoggedIn = Auth.isLoggedIn();
        // ... so on ...
    }
}

It compiles, but on rutime, it throws following error:

TypeError: _Services_Auth__WEBPACK_IMPORTED_MODULE_7__.default.isLoggedIn is not a function

What am I doing wrong?

Upvotes: 0

Views: 33

Answers (1)

AKX
AKX

Reputation: 168873

You're exporting the class itself, not an instance of it.

You'll want something like

class Auth {
    isLoggedIn() {
        return true;
    }
}

export default new Auth();

to export a singleton instance.

Upvotes: 0

Related Questions