Building iOS and Android Apps with the MongoDB Stitch React Native SDK
MongoDB Stitch provides native SDKs for both iOS (Swift) and Android (Java), but what if you want to create a single app that works on web, iOS, and Android? The answer is React Native and the MongoDB Stitch React Native SDK.
I've created a very simple React Native mobile app that demonstrates how to perform 3 tasks using Stitch:
Before using Stitch, you must require
the necessary Stitch SDK components:
const { Stitch, AnonymousCredential } = 
 require('mongodb-stitch-react-native-sdk');
const MongoDB = require('mongodb-stitch-react-native-services-mongodb-remote');

You can then connect to the Stitch app (using the Stitch app's ID) and the Atlas database:
_loadClient() {
 Stitch.initializeDefaultAppClient('TODO: greeting-xxxx').then(client => {
 this.setState({ client });
 const dbClient = client.getServiceClient(MongoDB.RemoteMongoClient.factory, "mongodb-atlas");
 this.setState({atlasClient : dbClient});
 this.setState({db : dbClient.db("greetings")});
 });
}

As I'm not interested in securing this app, but would still like each user to get a personalized experience, I take advantage of Stitch's anonymous login feature:
_onPressLogin() {
 this.state.client.auth.loginWithCredential(new AnonymousCredential()).then(user => {
 console.log(`Successfully logged in as user ${user.id}`);
 this.setState({ currentUserId: user.id })
 }).catch(err => {
 console.log(`Failed to log in anonymously: ${err}`);
 this.setState({ currentUserId: undefined })
 });
}

After the user has submitted their preferred name, I store it together with their unique ID in the greetings.names
collection:
const collection = this.state.db.collection("names");
collection.find({owner_id: this.state.currentUserId}, {limit: 1}).first().then(foundDoc => {
 if (foundDoc) {
 collection.updateOne(
 {owner_id: this.state.currentUserId}, 
 {owner_id: this.state.currentUserId, name: this.state.tempName}).then(result => {
 ...
 })
 })
 } else {
 collection.insertOne(
 {owner_id: this.state.currentUserId, 
 name: this.state.tempName}).then(result => {
 ...
 })
 })
 }
)

Finally, I call a Stitch Function (welcome
) to retrieve a personalized welcome message for the user:
this.state.client.callFunction("welcome").then(welcomeMessage => {
 this.setState({welcomeText: welcomeMessage});
})

This is the welcome
function in my Stitch app:
exports = function(){
 var collection = context.services.get("mongodb-atlas").db("greetings").
 collection("names");
 return collection.findOne({owner_id: context.user.id}).then(doc => {
 return("Hi, " + doc.name + " welcome to this awseome app!");
 });
};

You can recreate this Stitch and React Native app for your self by downloading it from GitHub and importing it into Stitch.
Creating your first Stitch app? Start with one of the Stitch tutorials.
Want to learn more about MongoDB Stitch? Read the white paper.