Home > Blockchain >  How to require and use a ES6 class in a next.js application?
How to require and use a ES6 class in a next.js application?

Time:04-11

I am working on a next.js app and I would like to move the code that interact with the database out of the api. I created a class that would be my manager:

class UserManager
{

    async findUser(email) {
        //some code
        return user;
    }

    async updateUser(user, reqBody) {
        //some other code
        //return something
    }
}
module.exports = UserManager;

and I am trying to use this class from my api

const UserManager = require('../../manager/UserManager');


export default async (req, res) => {
    const email = session.user.email;
    let UserManager = new UserManager();
    const user = await UserManager.findUser(email);
}

and I am getting this error

| ReferenceError: Cannot access 'UserManager1' before initialization
|   10 |     }
|   11 |     const email = session.user.email;
| > 12 |     let UserManager = new UserManager();
|      |                      ^

what's wrong with this approach? Am I requiring the class in the wrong way?

CodePudding user response:

This has nothing to do with modules or requre. Just variables and scope.

You have two variables named UserManager.

One is a const and is scoped to the module and contains the class.

The other is a let is is scoped to the exported arrow function; it shadows the const.

You’re trying to read the const inside the function but it is shadowed by the let. Since you are trying to read the const first (to call a function to get the value to assign to the let) you get an error because the rules of JS say that you’re reading the let (not the const you want).

Change the variable name you use for the let.

Idiomatic JS reserves variable names starting with a capital letter for classes and constructor functions (and React.js adds components to that list). The let variable is being assigned an instance of a class, not the class itself, so its name shouldn’t start with a capital letter.

let userManager = new UserManager();

I recommend using the eslint no-shadow rule to alert you when you make this error.


Aside: Your class doesn’t appear to track any internal state, it is just used to create an object to group some methods together (none of which even make use of this). It would probably be better off as a plain object rather than a class.

  • Related