React Native

Quickstart

Introduction

In this section you will learn how to get started with Back4App using an existing or new project using the React Native CLI. You will install the Parse SDK, initialize Parse using your App keys and make your first API Call saving and reading data objects from Back4App.

Prerequisites

To complete this tutorial, you will need:

Step 0 - Create your React Native project

There are two possible ways to create a project for React Native: Expo and React Native CLI.

The instructions depend on your development operating system, and whether you want to start developing for iOS or Android. For more information, check the official documentation here.

Install Expo CLI globally

npm install -g expo-cli

Create a new React Native project

expo init B4aProject

cd B4aProject
expo start

Step 1 - Install dependencies

On your React Native project let’s install the Parse Javascript SDK and the Async Storage. Make sure that you have installed npm or yarn in your system.

  • Back4App Parse SDK - To integrate your App with Back4app servers.
  • React Native Async Storage - To use Parse SDK, an AsyncStorage handler is required.

Run the following command on your Project root directory:

npm install parse @react-native-async-storage/async-storage --save

For iOS, use the CocoaPods to add the native RNAsyncStorage to your project:

cd ios & pod install

We are using @react-native-async-storage/async-storage but you can get your favorite AsyncStorage handler.

Step 2 - Get your App Keys

After creating your App on Back4App, go to your App’s Dashboard and get your App Keys under App Settings->Security & Keys(check the image below). Note that you will always need two keys to connect with Back4App, the Application ID and Javascript KEY.

Step 3 - Initialize Parse and connect to Back4App

Go to your App.js and initialize the Parse SDK using both the Application ID and the Javascript KEY (check the previous step).

App.js

1
2
3
4
5
6
7
8
9
10
// In a React Native application
import Parse from "parse/react-native.js";
import AsyncStorage from '@react-native-async-storage/async-storage';


//Initializing the SDK. 
Parse.setAsyncStorage(AsyncStorage);
//You need to copy BOTH the the Application ID and the Javascript Key from: Dashboard->App Settings->Security & Keys 
Parse.initialize('YOUR_APPLICATION_ID_HERE','YOUR_JAVASCRIPT_KEY_HERE');
Parse.serverURL = 'https://parseapi.back4app.com/';

Step 4 - Save and Read a simple Data Object

Your App is initialized and can securely connect to Back4app cloud services. Let’s create two simple functions inside the App.js to save and retrieve data to your Back4App Database.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
//This funciton will save a simple Person object
  async function addPerson() {
    try {
      //create a new Parse Object instance
      const newPerson = new Parse.Object('Person');
      //define the attributes you want for your Object
      newPerson.set('name', 'John');
      newPerson.set('email', '[email protected]');
      //save it on Back4App Data Store
      await newPerson.save();
    } catch (error) {
      console.log('Error saving new person: ', error);
    }
  }

The above addNewPerson method creates a new Parse.Object representing a person class, sets its properties, then saves it on Back4app cloud data store. Next, implement fetchPerson to fetch the person object you saved on Back4app.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const [person, setPerson] = useState(new Parse.Object('Person'));
//This function will retrieve a Person which the name is John
  async function fetchPerson() {
    //create your Parse Query using the Person Class you've created
    let query = new Parse.Query('Person');
    //run the query to retrieve all objects on Person class, optionally you can add your filters
    let queryResult = await query.findAll();
    //pick the first result 
    const currentPerson = queryResult[0];
    //access the Parse Object attributes
    console.log('person id: ', currentPerson.get('id'));
    console.log('person name: ', currentPerson.get('name'));
    console.log('person email: ', currentPerson.get('email'));
    setPerson(currentPerson);
  }

The above method will query a Parse.Object which has the attribute name equals to John. When the query resolves, you will be able to access the person attibutes using the get method.

At this point, your App.js file should look like this:

App.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import React, { useEffect, useState } from 'react';
import { View, Button, Text, SafeAreaView } from 'react-native';

// In a React Native application
import Parse from 'parse/react-native.js';
import AsyncStorage from '@react-native-async-storage/async-storage';


//Initializing the SDK
Parse.setAsyncStorage(AsyncStorage);
//Paste below the Back4App Application ID AND the JavaScript KEY
Parse.initialize('YOUR_APPLICATION_ID_HERE', 'YOUR_JAVASCRIPT_KEY_HERE');
//Point to Back4App Parse API address 
Parse.serverURL = 'https://parseapi.back4app.com/';

const App = () => {
  const [person, setPerson] = useState(new Parse.Object('Person'));

  async function addPerson() {
    try {
      //create a new Parse Object instance
      const newPerson = new Parse.Object('Person');
      //define the attributes you want for your Object
      newPerson.set('name', 'John');
      newPerson.set('email', '[email protected]');
      //save it on Back4App Data Store
      await newPerson.save();
    } catch (error) {
      console.log('Error saving new person: ', error);
    }
  }

  async function fetchPerson() {
    //create your Parse Query using the Person Class you've created
    let query = new Parse.Query('Person');
    //run the query to retrieve all objects on Person class, optionally you can add your filters
    let queryResult = await query.find();
    //the resul is an arry of objects. Pick the first result 
    const currentPerson = queryResult[0];
    //access the Parse Object attributes
    console.log('person id: ', currentPerson.get('id'));
    console.log('person name: ', currentPerson.get('name'));
    console.log('person email: ', currentPerson.get('email'));
    setPerson(currentPerson);
  }

  useEffect(() => {
    fetchPerson()
  }, []);

  return (
    <SafeAreaView>
      <View>
        <Text>Name: {person.get('name')}</Text>
        <Text>email: {person.get('email')}</Text>
        <Button title='Add person' onPress={addPerson} />
        <Button title='Fetch person' onPress={fetchPerson} />
        {/* Your other components here ....*/}
      </View>
    </SafeAreaView>
  )

}

export default App;

Step 5 - Test your App

  1. Open your project’s terminal.

  2. Run the project.

Run npx react-native run-android or npx react-native run-ios to open the application on your target platform. Then, click the button to add a new person first, then click to fetch this person.

Run expo start, and follow the instructions whether you want to check it on your browser, or on your device using Expo app.

You’ve saved and retrieved a data object from Back4App. You can also check the data on your App Dashboard and clicking on Person class.

  • In case you don’t have a device or a simulator to test it, you can also run it on a web page.
  • Run npm start and press w.

TroubleShooting

Some common error messages when running your project:

Metro has encountered an error: while trying to resolve module “idb-keyval’ from file

Solution: Go to the metro.conf.js file and change it to this one:

1
2
3
4
const { getDefaultConfig } = require("@expo/metro-config");
const defaultConfig = getDefaultConfig(__dirname);
defaultConfig.resolver.assetExts.push("cjs");
module.exports = defaultConfig;

Unable to resolve module ‘EventEmitter’

Solution: Go to the file: node_modules\parse\lib\react-native\EventEmitter.js and change this row:

 var EventEmitter = require('../../../react-native/Libraries/vendor/emitter/EventEmitter');

to this:

 import EventEmitter from 'react-native/Libraries/vendor/emitter/EventEmitter';

In the same file EventEmitter.js, change the following row:

module.exports = EventEmitter;

to this:

export default EventEmitter;

What to do next

As you have seen, the easiest way to integrate Back4App into your React Native project is through the Parse Javascript SDK. The Parse SDK delivers an excellent development experience through a lightweight and easy-to-use layer that provides minimal configuration, code re-usability, and native optimizations for Android and iOS.

You will find on the following guides how to use features like data storage(relational), real-time capabilities(using a React Hook), local data storage, cloud functions(fully integrated with your database), authentication, file storage, and more. As a next step, we recommend you explore the data storage capabilities and start enjoying the power of Parse Queries.