Skip to content

Instantly share code, notes, and snippets.

@jchris
Last active May 4, 2018 04:29
Show Gist options
  • Save jchris/3c32524577deff3d69aa to your computer and use it in GitHub Desktop.
Save jchris/3c32524577deff3d69aa 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.

@atvenu
Copy link

atvenu commented Mar 30, 2016

Thanks @adamski

@npomfret
Copy link

Did anyone solve the problem of not being able to access http://lite.couchbase./? I just get a network error. I've looked at some other examples out there like the cordova plugin, but can't see what they've done differently.

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