MongoDB Stitch Authentication in React Native


June 2020

I wrote in a previous article about some quirks of MongoDB Stitch Username / Password authentication in React, particularly the need to use a ternary operator to prevent a "multiple initialization" error:

// MongoDB Stitch initialization
const APP_ID = "<your-app-id-from-stitch>";
const client = Stitch.hasAppClient(APP_ID)
? Stitch.getAppClient(APP_ID)
: Stitch.initializeDefaultAppClient(APP_ID);

When I started working on a React Native version of the same app, that same issue resurfaced and required a new solution.

That's because — unlike its Browser counterpart — the Native version of MongoDB Stitch SDK returns a promise on initialization (though it does not on subsequent invocations).

So here follows a different approach for React Native.

First of all, of course we want to import the SDK:

const { Stitch } = require("mongodb-stitch-react-native-sdk");

Then we are going to create two separate functions:

loadClient() {
Stitch.initializeDefaultAppClient("<your-app-id-from-stitch>").then(client => {
this.setState({ client });
const dbClient = client.getServiceClient(
MongoDB.RemoteMongoClient.factory,
"<your-api-name-from-stitch>"
);
this.setState({ dbClient });
this.setState({ db: dbClient.db("<your-database-name>") });
});
}
getClient() {
const client = Stitch.getAppClient("<your-app-id-from-stitch>");
this.setState({ client });
const dbClient = client.getServiceClient(
MongoDB.RemoteMongoClient.factory,
"<your-api-name-from-stitch>"
);
this.setState({ dbClient });
this.setState({ db: dbClient.db("<your-database-name>") });
}

Finally, on page load we are going to trigger the first (promise-based) function only when Stitch.hasAppClient("<your-app-id-from-stitch>") is falsey. Otherwise we will use getClient.

componentDidMount() {
Stitch.hasAppClient("<your-app-id-from-stitch>")
? this.getClient()
: this.loadClient();
}

I hope this helps! If you have any questions or comments, feel free to reach me on Twitter.

© 2023 Stefano Picker