14

in my react-native app I currently have a User class in which I define a current user as below:

class User {
    static currentUser = null;

    //other relevant code here

    static getCurrentUser() {
        return currentUser;
    }
}

export default User;

In a different class, I am trying to access the set value of this currentUser. I cannot figure out how to correctly call this function; I am getting the error User.getCurrentUser is not a function. Should I be calling this function in a different way?

var User = require('./User');

getInitialState: function() {

    var user = User.getCurrentUser();

    return {
        user: user
    };


},

3 Answers 3

10

You are mixing import / export styles. You should either change your import to

var User = require('./User').default

or

import User from './User'

Or change your export:

module.exports = User
Sign up to request clarification or add additional context in comments.

Comments

6

I think you also forgot the this keyword for returning the static "currentUser" field:

class User {
  constructor() {}

  static currentUser = {
    uname: 'xxx',
    firstname: 'first',
    lastname: 'last'
  };

  static getCurrentUser() {
    return this.currentUser;
  }
}

console.log(User.getCurrentUser());

1 Comment

For static variables "this" is not a valid source. In this case User.currentUser is the right format.
0

Try arrow function:

class User {
    static currentUser = null;

    static getCurrentUser = () => {
        return currentUser;
    }
}
export default User;

1 Comment

Please put your answer always in context instead of just pasting code. See here for more details.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.