DEV Community

Zain Ahmed
Zain Ahmed

Posted on

In-App Chatting in React Native

We often use a feature like chatting in most of the Mobile Application whether is related to banking app, Ecommerce and/or chatting apps. Its required enough time to build a chatting feature for any App in different Tech Stack, "What if i tell you a easiest way to integrate/build In App Chatting feature which required almost 15 mins to build and reliable.

ZEGOCLOUD is a library which offer may feature like Audio/Video calling, Live Streaming, Super Board, Cloud recording and much more.
In-App Chatting is one of them and I must say in my 4 years of experience I found the the platform easy to adopt in most of the features.

Here are some points which you should know before choosing any library to integrate In-App Chatting feature.

Ultra-low latency

Have you ever miss important messages due to law latency? well in ZEGOCLOUD you don't need to worry about is as t delivers real-time messages to users with an ultra-low latency as low as 200 ms.

Massive concurrency

One of the main issue is how to handle concurrent messages when the count is in millions, well ZEGOCLOUD handle it pretty perfectly as needs of large-scale and highly demanding live communication events

Instruction/Steps

  • Go to ZEGOCLOUD and make a account
  • Go to dashboard and create a APP
  • Select In-app chatting feature
  • Go to Service Management option from dashboard and select In-App chatting feature in app chatting option
  • Activate it activation
  • Copy and save AppID for later use
  • Run command npm i zego-zim-react-native to install library.
  • Import SDK in Component import ZIM from 'zego-zim-react-native';
  • Create a instance of ZIM using method create, You need AppID **and appSign which you can get from dashboard appSign
  • I have define some state for later user component states
  • Create a login function that will login user to application login
  • Create sendMessage function that will help to send message to other user sendMessage
  • A useEffect is define to handle some realtime events, If user connection state change the event connectionStateChanged will notify us, If any error occur the event error will notify us & if user get any message from other user the event receivePeerMessage will have that received message from where we can show it on UI receivePeerMessage
  • We also have a logout & destroy method which will help to logout user when user leave screen and destroy the ZIM instance. Here is my component
import React, { useEffect, useState } from 'react';
import { Button, TextInput, View, Text } from 'react-native';
import ZIM from 'zego-zim-react-native';
ZIM.create({ appID: ******, appSign: '***********************' })
const zim = ZIM.geInstance();

const VideoCalling = (props) => {
    // const zim = ZIM.geInstance();
    useEffect(() => {
        try {
            // ZIM.caller({ appID: '177503827', appSign: '4813ca648e686180b2d6e12956bf6ba8465112251090af88228754356c3939b1' });
        } catch (error) {
            console.log(error)
        }
    }, [])
    const [userInfo, setUserInfo] = useState({
        userID: '', //
        userName: '',
        token: ''
    })
    const [state, setState] = useState({
        message: '',
        otherUserId: ''
    })

    useEffect(() => {
        // Set up and listen for the callback for receiving error codes.  
        zim.on('error', function (zim, errorInfo) {
            console.log('error', errorInfo.code, errorInfo.message);
        });

        // Set up and listen for the callback for connection status changes. 
        zim.on('connectionStateChanged', function (zim, { state, event, extendedData }) {
            console.log('connectionStateChanged', state, event, extendedData);
        });

        // Set up and listen for the callback for receiving one-to-one messages. 
        zim.on('receivePeerMessage', function (zim, { messageList, fromConversationID }) {
            console.log('receivePeerMessage', messageList, fromConversationID);
        });

        return () => {
            zim.logout();
            zim.destroy();
        }
    }, [])

    const handleLogin = () => {
        try {
            zim.login(userInfo, token)
                .then(function () {
                    // Login successful.
                })
                .catch(function (err) {
                    // Login failed.
                });
        } catch (error) {

        }
    }

    const sendMessage = () => {
        try {
            const messageTextObj = { type: 1, message: state.message };
            zim.sendMessage(messageTextObj, toUserID)
                .then(function ({ message }) {
                    // Message sent successfully.
                })
                .catch(function (err) {
                    // Failed to send the message.
                });
        } catch (error) {

        }
    }

    const onStateHandleChange = (key, value) => {
        setState({ ...state, [key]: value })
    }
    const onUserObjHandleChange = (key, value) => {
        setUserInfo({ ...state, [key]: value })
    }

    return (
        <View style={{ padding: 5 }}>
            <View>
                <View style={{ paddingVertical: 5 }}>
                    <Text>UserID</Text>
                    <TextInput
                        value={userInfo.userID}
                        onChangeText={(value) =>
                            onUserObjHandleChange('userID', value)}
                        style={{ borderWidth: 1 }} />
                </View>
                <View style={{ paddingVertical: 5 }}>
                    <Text>User Name</Text>
                    <TextInput
                        value={userInfo.userName}
                        onChangeText={(value) =>
                            onUserObjHandleChange('userName', value)}
                        style={{ borderWidth: 1 }} />
                </View>
                <View style={{ paddingVertical: 5 }}>
                    <Text>Token</Text>
                    <TextInput
                        value={userInfo.token}
                        onChangeText={(value) =>
                            onUserObjHandleChange('token', value)}
                        style={{ borderWidth: 1 }} />
                </View>
                <Button title="Login" onPress={handleLogin} />
                <View>
                    <View style={{ paddingVertical: 5 }}>
                        <Text>Other person ID</Text>
                        <TextInput
                            value={state.otherUserId}
                            onChangeText={(value) =>
                                onStateHandleChange('otherUserId', value)}
                            style={{ borderWidth: 1 }} />
                    </View>
                    <Button title="Submit" />
                </View>
                <View>
                    <View style={{ paddingVertical: 5 }}>
                        <Text>Message</Text>
                        <TextInput
                            value={state.message}
                            onChangeText={(value) =>
                                onStateHandleChange('message', value)}
                            style={{ borderWidth: 1 }} />
                    </View>
                    <Button title="Send" onPress={sendMessage} />
                </View>
            </View>
        </View>
    );
}

export default VideoCalling;
Enter fullscreen mode Exit fullscreen mode

Links:

React Native In-App chatting Doc
Sample Codebase

1
2
Image description

Top comments (0)