==

Q-Consultation for every industry

Securely hold virtual meetings and video conferences

Learn More>

Want to learn more about our products and services?

Speak to us now

How to Build a Chat App with QuickBlox React Native SDK

Oleksandr Shvetsov
24 Nov 2021
Icons for React Native and chat bubbles

Note: This blog has been updated since it was originally published in December 2019.

Chat applications provide an easy way for people to communicate with each other, wherever they are in the world. For businesses, the benefits of connecting employers with each other via in-app chat or providing customers with direct real-time communication are immense. Chat apps enhance customer engagement and employee productivity, help facilitate transactions and provide a positive user experience.

QuickBlox provides SDKs that allow you to effortlessly add chat to any app. Our React Native chat SDK enables feature-rich messaging functionality, as well as audio and video chat. The React Native framework allows you to save time and money because you only need to build a single chat app that will work across platforms. In the following tutorial the QuickBlox team provides a step-by-step guide on how to use our robust chat SDK for React Native to build a modern messenger app.

Before we get started…

Building any application with any QuickBlox SDK requires you first to create a QuickBlox application. To create an application you need a QuickBlox account – you can register at https://admin.quickblox.com/signup or login if you already have an account. Then create your QuickBlox app and get app credentials. You will need them to identify your app.

Set Up

To begin building your React Native chat app, you first need to create a new project.

Run:

npx react-native init AwesomeChatApp

To manage the application state we will use redux (with react-redux – react bindings for redux). To keep the application state persistent after reloads / restart we will use redux-persist. To make it work, we will specify which storage engine we want to use. We will need async-storage. For navigation, we will use the popular and easy-to-use library react-navigation, which comes with it’s own set of dependencies, so we will need to install these as well:

Install the required packages in your React Native project

To install the Quickblox React Native SDK you need to run:

npm install
quickblox-react-native-sdk --save.

The current version of the QuickBlox React Native SDK supports iOS version 12.0 onwards. Therefore, we need to update the iOS/ Podfile: platform :ios, '12.0'

To install iOS dependencies we should enter ios folder (in terminal) and run pod install

Once you have QuickBlox application credentials (Application ID, Authorization key, Authorization secret, and Account key) you can initialize the QuickBlox React Native SDK:

const appSettings = {
  appId: '',
  authKey: '',
  authSecret: '',
  accountKey: '',
  apiEndpoint: '', // optional
  chatEndpoint: '' // optional
};

QB.settings
  .init(appSettings)
  .then(function () {
    // SDK initialized successfully
  })
  .catch(function (e) {
    // Some error occured, look at the exception message for more details
  });

Once the SDK is initialized – it is ready to work. In order to perform some operations using the QuickBlox SDK, you need to be signed in. Run:

QB.auth
  .login({
    login: 'yourlogin',
    password: 'yourpassword'
  })
  .then(function (info) {
    // signed in successfully, handle info as necessary
    // info.user - user information
    // info.session - current session
  })
  .catch(function (e) {
    // handle error
  });

Now we are able to get dialogs, retrieve users, etc. But in order to send and receive messages in real-time, we need to be connected over XMPP. To connect to a chat call:

QB.chat
  .connect({
    userId: 12345,
    password: 'passw0rd!'
  })
  .then(function () {
    // connected successfully
  })
  .catch(function (e) {
    // some error occurred
  });

So now we are ready to chat.

Ready to Send your First Message?

You can make sure if you are connected to chat at any moment by calling:

QB.chat
  .isConnected()
  .then(isConnected => {
    // isConnected - boolean value
    // true - connected to chat
    // false - not connected
  })
  .catch(e => {
    // some error occured
  })

But in order to receive notifications about new messages, you need to assign an event handler to process events accordingly. The QuickBlox SDK contains several modules and some of them can emit events.

TIP: You can check if a module can emit events, by seeing whether it contains the property “EVENT_TYPE” with a list of the available events.

To assign an event handler that will process new messages, run this:

import { NativeEventEmitter } from 'react-native'
import QB from 'quickblox-react-native-sdk'

function connectionEventHandler(event) {
  const { type, payload } = event
  // handle as necessary
}

function receivedNewMessage(event) {
  const { type, payload } = event
  // event.type - name of the event
  // event.payload - event data. Received message in this case.
}

const emitter = new NativeEventEmitter(QB.chat)

const QBConnectionEvents = [
  QB.chat.EVENT_TYPE.CONNECTED,
  QB.chat.EVENT_TYPE.CONNECTION_CLOSED,
  QB.chat.EVENT_TYPE.CONNECTION_CLOSED_ON_ERROR,
  QB.chat.EVENT_TYPE.RECONNECTION_FAILED,
  QB.chat.EVENT_TYPE.RECONNECTION_SUCCESSFUL,
]

QBConnectionEvents.forEach(eventName => {
   emitter.addListener(eventName, connectionEventHandler)
})

emitter.addListener(QB.chat.EVENT_TYPE.RECEIVED_NEW_MESSAGE, receivedNewMessage)

Now we are able to process new messages received or connection changes.

In order to send messages, we need to specify where we want to send them, i.e. specify the dialogue. But do we have some dialogues? Get dialogues available for your user:

QB.chat
  .getDialogs()
  .then(function (result) {
    // result.dialogs - array of dialogs found
    // result.skip - number of items skipped
    // result.limit - number of items returned per page
    // result.total - total amount of items
  })
  .catch(function (e) {
    // handle error
  });

Putting It All Together

Let’s imagine there are no dialogues returned for our user. So we should create a new one to start messaging. In order to create a dialogue, we need to specify the dialogue participants.

Let’s get users to find someone to chat with:

const sort = {
  ascending: false,
  field: QB.users.USERS_FILTER.FIELD.UPDATED_AT,
  type: QB.users.USERS_FILTER.TYPE.DATE
}

QB.users
  .getUsers({ sort })
  .then(function (result) {
    // result.users - array of users found
    // result.page - page of results
    // result.perPage - how much items returned per page
    // result.total - total amount of items
  })
  .catch(function (e) {
    // handle error
  });

Now we can pick a user from results and create a new chat.

QB.chat
  .createDialog({
    type: QB.chat.DIALOG_TYPE.CHAT,
    occupantsIds: [12345] // user.id
  })
  .then(function (dialog) {
    // handle as necessary, i.e.
    // subscribe to chat events, typing events, etc.
  })
  .catch(function (e) {
    // handle error
  });

You can also subscribe to “typing” events and message status (“read,” “delivered”) events.

Now we can send a message in a created dialogue. Let’s try it out:

const message = {
  dialogId: dialog.id,
  body: 'Hey there!',
  saveToHistory: true
};

QB.chat
  .sendMessage(message)
  .then(function () { /* sent successfully */ })
  .catch(function (e) { /* handle error */ })

Now your chat functionality is working. If your message is sent successfully, you can expect your opponent to receive your message and send you a response. Then you will receive a notification when there is a new message in this dialogue.

Wrapping Up

QuickBlox SDKs allow you to build modern messaging apps that will engage your customers. No need to build from scratch, our feature-rich React Native chat SDK provides a complete kit for everything you need to start building chat today.

Check out our React Native documentation & code samples.

For technical queries about using our chat SDK for React Native or recommendations for our product or documentation please submit a ticket to our support team.

Contact us to learn more about how QuickBlox can support your communication deeds.

Have Questions? Need Support?

Join the QuickBlox Developer Discord Community, where you can share ideas, learn about our software, & get support.

Join QuickBlox Discord

Leave a Comment

Your email address will not be published. Required fields are marked *

Read More

Ready to get started?

QUICKBLOX
QuickBlox post-box