Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

singleton object in react native

Tags:

react-native

I'm new in react native.I want store multiple small small strings to common singleton object class and want to access it from singleton object for all component. Can anyone help me singleton object implementation for react native.

Ex

Component 1 -- Login button -- >> success --> need to store userID into singleton object.

Component 2 --> get stored userID from singleton object. How can i implement it.

like image 674
Ravindhiran Avatar asked Jun 23 '17 10:06

Ravindhiran


People also ask

What is singleton in react?

Singletons are classes which can be instantiated once, and can be accessed globally. This single instance can be shared throughout our application, which makes Singletons great for managing global state in an application.

What is meant by singleton object?

A Singleton object is an object which defines a single object of a class. A singleton object provides an entry point to your program execution. If you do not create a singleton object in your program, then your code compile successfully but does not give output.

Why do we need singleton objects?

The Singleton's purpose is to control object creation, limiting the number of objects to only one. Since there is only one Singleton instance, any instance fields of a Singleton will occur only once per class, just like static fields.

How the singleton object is created?

To create the singleton class, we need to have static member of class, private constructor and static factory method. Static member: It gets memory only once because of static, itcontains the instance of the Singleton class. Private constructor: It will prevent to instantiate the Singleton class from outside the class.


2 Answers

Here is a simple way of doing it...

export default class CommonDataManager {      static myInstance = null;      _userID = "";       /**      * @returns {CommonDataManager}      */     static getInstance() {         if (CommonDataManager.myInstance == null) {             CommonDataManager.myInstance = new CommonDataManager();         }          return this.myInstance;     }      getUserID() {         return this._userID;     }      setUserID(id) {         this._userID = id;     } } 

And here is how to use it...

import CommonDataManager from './CommonDataManager';   // When storing data. let commonData = CommonDataManager.getInstance(); commonData.setUserID("User1");   // When retrieving stored data. let commonData = CommonDataManager.getInstance(); let userId = commonData.getUserID(); console.log(userId); 

Hope this works out for you :)

like image 156
Yeshan Jay Avatar answered Sep 30 '22 15:09

Yeshan Jay


I suggest making a static class that stores data using AsyncStorage. You mentioned in a comment that you are already using AsyncStorage, but don't like spreading this functionality throughout your app. (i.e. try-catches all over the place, each component needing to check if a key is available, etc.) If this functionality were in a single class, it would clean up your code a lot.

Another bonus to this approach is that you could swap out the implementation pretty easily, for example, you could choose to use an in-memory object or AsyncStorage or whatever and you would only have to change this one file

NOTE: AsyncStorage is not a safe way to store sensitive information. See this question for more info on the security of AsyncStorage and alternatives.

That said, this is how I imagine a global data holder class might look:

export default class dataManager {   static storeKeyValue(key, value) {     // your choice of implementation:     // check if key is used     // wrap in try-catch     // etc.   }    static getValueForKey(key) {     // get the value out for the given key   }    // etc... } 

Then to use this class anywhere in your app, just import wherever it's needed like so:

import dataManager from 'path/to/dataManager.js';  // store value dataManager.storeKeyValue('myKey', 'myValue');  // get value const storedValue = dataManager.getValueForKey('myKey'); 

EDIT: Using Flux, Redux, or a similar technology is probably the preferred/suggested way to do this in most cases, but if you feel the Singleton pattern works best for your app then this is a good way to go. See You Might Not Need Redux

like image 41
Danny Harding Avatar answered Sep 30 '22 16:09

Danny Harding