How to call a method from response allDocs(err, response)

I created an app that uses pouchdb. When it starts up and the localdb is empty I want the app to load data into the localdb from a json file. If there is data in the localdb I want the app to sync from a remote source. All separate functions work. So it can load from the JSON file and it can sync when I call the methods from seperate buttons.
But in the startup checks of the app I’m doing something wrong:

  startupCheck()
  {
    console.log('startupCheck start');
    this._localdb.allDocs(function(err, response)
    {
      if (err)
      {
        return console.log(err);
      }
      if (response.rows.length == 0)
      {
        // no records in localdb
        console.log('Load initial data from json file');
        this.jsonInit();
      }
      else
      {
          // there are records. now check for updates on server
          console.log('Sync data from server to localdb');
          this.replicateFromRemote();
      }
    });
    console.log('startupCheck end');
  }

The error:

ERROR Error: Uncaught (in promise): TypeError: Unable to get property ‘replicateFromRemote’ of undefined or null reference.
TypeError: Unable to get property ‘replicateFromRemote’ of undefined or null reference

It seems I cannot make a call to this._anyfunction() from a response. I also tried setting a flag like:

this._dbNeedsInit = true;

Also then I will get a null reference error.
Any suggestions?

Where do

and

live/exist?

Try to change
this._localdb.allDocs(function(err, response)
to
this._localdb.allDocs((err, response) =>

After i think you should be able to access this.

1 Like

The all live in the same home.ts file. Sveinla handed me the solution. It’s working fine now. What it is I did, I wouldn’t know :slight_smile:

Google for “arrow functions” and read a bit. In your code this was something different.

1 Like

Definitely check what “this” contextually in your case, use {}.bind(this) as necessary or other methods to make sure this refers to the scope where those functions live.

Also use promises if possible, its way easier to read the code that way.