Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save catalinmiron/b8577a6f03e8c815b448 to your computer and use it in GitHub Desktop.
Save catalinmiron/b8577a6f03e8c815b448 to your computer and use it in GitHub Desktop.
Couchbase Lite with React Native

Couchbase Lite with React Native

I went into this expecting a challenge but it was easy. Basically, Couchbase Lite has always had an optional HTTP listener that you can connect to from inside your app at http://lite.couchbase./mydatabase/. React Native has a fine XHR module and encourages using fetch so getting your app to sync can be as easy as adding some API calls to keep JSON in the database.

We haven't done a full example yet, but in the spirit of possiblity, here are quick instructions to connect Couchbase Lite iOS with a React Native app (generated from their cli).

#import "CouchbaseLite/CouchbaseLite.h"
#import "CouchbaseLiteListener/CBLListener.h"
#import "CBLRegisterJSViewCompiler.h"
  • Add a function to AppDelegate.m to launch Couchbase Lite
- (void)launchCouchbaseLite
{
  NSLog(@"Launching Couchbase Lite...");
  CBLManager* dbmgr = [CBLManager sharedInstance];
  CBLRegisterJSViewCompiler();
  NSLog(@"Couchbase Lite url = %@", dbmgr.internalURL);
}
  • Call this function from application didFinishLaunchingWithOptions:
[self launchCouchbaseLite];
  • Now in your JavaScript code you can create a new database with a PUT (here's a fancy version that does a GET first to check if the PUT is necessary):
var dbURL = "http://lite.couchbase./mydb/"
fetch(dbURL).then((response) => {
  if (response.status !== 200) {
    return fetch(dbURL, {method:"PUT"})
    .then((response) => response.json()).then((data) => {
      console.log("create db", data)
      return data;
    }).catch()
  }
})
  • You can create documents by POSTing to the database:
fetch(dbURL, {method:"POST", body : JSON.stringify({hello:"world"})})
.then((response) => response.json()).then((data) => {
  console.log("create document", data)
  return data;
}).catch()
  • And get all documents with a GET query:
fetch(dbURL + "_all_docs?include_docs=true")
.then((response) => response.json()).then((data) => {
  var docs = data.rows.map((row) => (row.doc));
  console.log("all documents", docs);
  return docs;
}).catch()

To see something like this in context, you could try my branch of marucc's demo app here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment