Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access static variable from another class in React-Native app?

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
    };


},
like image 831
user3802348 Avatar asked May 30 '16 04:05

user3802348


People also ask

How to make a react native app with React Native CLI?

We are going to use react-native init to make our React Native App. Assuming that you have node installed, you can use npm to install the react-native-cli command line utility. Open the terminal and go to the workspace and run If you want to start a new project with a specific React Native version, you can use the --version argument:

Which variable is initialized in the first screen in React Native?

We have a global.MyVar variable initialized in the first screen which can be accessed from First Screen as well as from the Second Screen. Getting started with React Native will help you to know more about the way you can make a React Native project.

What is a static property in react?

Understanding `static` in React. How I stumbled into learning something | by dave.js | Frontend Weekly | Medium TL;DR: Static properties are properties of a class, not of an instance of a class. In university, I was taught object-oriented programming in Java. Like most beginners, the first thing I learned was some version of this:

How to create global scope variables in React Native?

In React Native we can make any variable Global Scope Variables by just putting global. prifix. For an Example. If we have myvar which is a local variable and accessible only from the same class. and if we have global.myvar then it becomes global and can be accessed from any class of the application.


Video Answer


1 Answers

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
like image 115
Balázs Édes Avatar answered Sep 21 '22 22:09

Balázs Édes