Ataomega Ataomega - 1 year ago 308
React JSX Question

React native: Always running component

I don't know actually, how to name this question!

I've a JS file in react native that fetches data from server and compares it to local database. i need this to run simultaneously, how can i achieve that? when app starts, that should run, changing views (navigation to other components) should not destroy it, it should still be running.

Any solutions?

Answer Source

You are explaining a design pattern of something called: Singleton.

Here's how to do it:

let instance = null;

class Singleton{  
    constructor() {
              instance = this;

        // to test whether we have singleton or not
        this.time = new Date()

        return instance;

Testing singleton On above class we have defined a time property to make sure we have singleton working properly.

 let singleton = new Singleton()

   let singleton = new Singleton();

If it prints the same time for both the instances, it means we have a working singleton.

Now, you can load your server data asynchronously inside the singleton and do whatever you'd like to do with it. Anytime you try to access the singleton class, it will be the same instance and it will not be instantiated more than once. In other words, it will not be destroyed.


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download