mongodb-stitch-react-native-sdk v4.8.0
MongoDB Stitch React Native SDK
The official MongoDB Stitch React Native SDK for JavaScript/TypeScript.
Index
Documentation
Discussion
Installation
NPM
Run the following in the root directory of your NPM project.
npm install mongodb-stitch-react-native-sdk
This will start you off with the core SDK functionality as well as the remote MongoDB service.
For customized dependencies use the following:
npm install mongodb-stitch-react-native-core
npm install mongodb-stitch-react-native-services-aws
npm install mongodb-stitch-react-native-services-http
npm install mongodb-stitch-react-native-services-mongodb-remote
npm install mongodb-stitch-react-native-services-twilio
Example Usage
Creating a new app with the SDK (React Native)
Set up an application on Stitch
- Go to https://stitch.mongodb.com/ and log in to MongoDB Atlas.
- Create a new app in your project with your desired name.
- Go to your app in Stitch via Atlas by clicking Stitch Apps in the left side pane and clicking your app.
- Copy your app's client app id by going to Clients on the left side pane and clicking copy on the App ID section.
- Go to Providers from Users in the left side pane and edit and enable "Allow users to log in anonymously".
Set up a React Native project
- Ensure that you have
npm
installed. See npmjs.com. - If you don't already have Create React Native App installed, run
npm install -g create-react-native-app
- Initialize a new React Native project with
create-react-native-app YourProjectName
. - Go to the new project with
cd YourProjectName
. Add the MongoDB Stitch React Native SDK by running
npm install mongodb-stitch-react-native-sdk
.In
App.js
, replace the existing code with the following, replacing<your-client-app-id>
with the id you retrieved when setting up the application in MongoDB Stitch:
const React = require('react');
const { Button, StyleSheet, Text, View } = require('react-native');
const { Stitch, AnonymousCredential } = require('mongodb-stitch-react-native-sdk');
export default class App extends React.Component {
constructor(props) {
super(props);
this.state={
currentUserId: undefined,
client: undefined
};
this._loadClient = this._loadClient.bind(this);
this._onPressLogin = this._onPressLogin.bind(this);
this._onPressLogout = this._onPressLogout.bind(this);
}
componentDidMount() {
this._loadClient();
}
render() {
let loginStatus = "Currently logged out."
if(this.state.currentUserId) {
loginStatus = `Currently logged in as ${this.state.currentUserId}!`
}
loginButton = <Button
onPress={this._onPressLogin}
title="Login"/>
logoutButton = <Button
onPress={this._onPressLogout}
title="Logout"/>
return (
<View style={styles.container}>
<Text> {loginStatus} </Text>
{this.state.currentUserId !== undefined ? logoutButton : loginButton}
</View>
);
}
_loadClient() {
Stitch.initializeDefaultAppClient('<your-client-app-id>').then(client => {
this.setState({ client });
if(client.auth.isLoggedIn) {
this.setState({ currentUserId: client.auth.user.id })
}
});
}
_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 })
});
}
_onPressLogout() {
this.state.client.auth.logout().then(user => {
console.log(`Successfully logged out`);
this.setState({ currentUserId: undefined })
}).catch(err => {
console.log(`Failed to log out: ${err}`);
this.setState({ currentUserId: undefined })
});
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
- Run the app by running
npm start
and following the instructions in the terminal. You may need to runnpm install
beforenpm start
works correctly.
Using the SDK
Initialize the SDK
- When your app has started, run the following code to initialize the Stitch SDK, replacing
<your-client-app-id>
with your Stitch application's client app ID:
const { Stitch, AnonymousCredential } = require('mongodb-stitch-react-native-sdk');
Stitch.initializeDefaultAppClient('<your-client-app-id>').then(client => {
// use the client
});
Please take note that unlike the other Stitch SDKs, this client initialization method is asynchronous. This is due to the fact that the client stores persisted authentication information using React Native's AsyncStorage system.
- To get an already-initialized client to use for logging in and communicating
with Stitch, use
Stitch.defaultAppClient
const stitchClient = Stitch.defaultAppClient;
Logging In
- We enabled anonymous log in, so let's log in with it; add the following anywhere in your code:
const client = Stitch.defaultAppClient;
console.log("logging in anonymously");
client.auth.loginWithCredential(new AnonymousCredential()).then(user => {
console.log(`logged in anonymously as user ${user.id}`)
});
- When running this code, you should see the following in your standard out:
logging in anonymously
logged in anonymously as user 58c5d6ebb9ede022a3d75050
Executing a function
- Once logged in, executing a function happens via the
StitchAppClient
'scallFunction()
method
client.callFunction("echoArg", ["Hello world!"]).then(echoedResult => {
console.log(`Echoed result: ${echoedResult}`);
})
- If you've configured your Stitch application to have a function named "echoArg" that returns its argument, you should see a message like:
Echoed result: Hello world!
Getting a StitchAppClient without Stitch.getDefaultAppClient
In the case that you don't want a single default initialized StitchAppClient
,
you can use the following with as many client app IDs as you'd like to
initialize clients for multiple app IDs:
Stitch.initializeAppClient("<your-client-app-id>").then(client => {
// use the client
});
You can use the client here or anywhere else in your app by using the following:
const client = Stitch.getAppClient("<your-client-app-id>");
Closing the StitchAppClient
The client maintains some background processes in the event loop that must be
shutdown when the client is no longer needed. Simply call close
on the client
when you are done with the client:
client.close();
4 years ago
4 years ago
4 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago