Reputation: 2060
Actually I am a Android Native Developer. I am new to React-Native. In Java i keep the users data and others data in Singleton Class and access from other activities. Then how i achieve this process in React native for access data's from other components or any alternative of singleton in React native.
I just try this but i received the error like getInstance() not defined.
class AppDelegate {
log = "This is AppDelegate";
static myInstance = null;
static getInstance() {
if (AppDelegate.myInstance == null) {
AppDelegate.myInstance = new AppDelegate();
}
return this.myInstance;
}
}
Thank you.
Upvotes: 4
Views: 2588
Reputation: 142
If you need a singleton don't use a class at all. Export the methods as a function instead.
// File app-delegate.js
let privateIstanceValue;
export const method1 = () => //do something;
export const method2 = () => //do something again;
Import using import * as
import * as appDelegate from './app-delegate.js';
Upvotes: 0
Reputation: 15851
Imports are cached, so if you export a class, the class will be cached, if you export an instance, the instance will be cached
Upvotes: 3
Reputation: 222989
React is UI library, this isn't its responsibility. The question affects any JavaScript application, not only React.
JavaScript modules and ES modules in particular are evaluated only once under normal circumstances, this makes exports singletons:
// exported for extensibility
export class AppDelegate {...}
// a singleton
export default new AppDelegate;
Singleton class is potentially an antipattern in JavaScript. If there's a need for one object, it could be written as object literal.
Upvotes: 4