Simple way create chat application in react native nodejs and MongoDB
In this tutorial we learn how we can create chat module for real time communication. Most of clients demands for chat in their mobile application So as a developer i try to search a easy and reliable way to complete the task so today in this tutorial i will tell you how we can create chat application in react native, nodejs and MongoDB database in easy steps. For chat application i have set up front end in react native for user interface and nodejs for back end to save the response in database. so let’s begin:
Highlights:
- install chat library
- set up code with react-native-gifted-chat
- set up nodejs code for save data with rest API
1. Install chat library
I have set up this code with help of “react-native-gifted-chat”. You can install it with this command.
1 |
npm i react-native-gifted-chat |
You can check full documentation here react-native-gifted-chat
2. set up code with react-native-gifted-chat
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 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 |
import React, { useState, useCallback, useEffect } from 'react' import {View} from 'react-native'; import { GiftedChat } from 'react-native-gifted-chat' import AsyncStorage from '@react-native-async-storage/async-storage'; import Spinner from 'react-native-loading-spinner-overlay'; const NewChat = (props) => { const [messages, setMessages] = useState([]); const [loading, setLoading] = React.useState(true); const [user, setUser] = React.useState({}); useEffect(() => { let isMounted = true; // note mutable flag const getDoc = async () => { await AsyncStorage.getItem("userData").then(async (data) => { if (isMounted) { console.log(JSON.parse(data)) setUser(JSON.parse(data)); // add conditional check let val = JSON.parse(data) console.log(val._id) if(val._id){ let sdata = { method: 'POST', //credentials: 'same-origin', //mode: 'same-origin', body: JSON.stringify({ "channel_id":'channel_id' }), headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', //'X-CSRFToken': cookie.load('csrftoken') } } await fetch('http://localhost:3000/api/fetch_all_messages', sdata) .then((response) => response.json()) .then(async (json) => { console.log(json) if(json.status && json.data && json.data.length>0) { let arr = [] let count = 1; json.data.map((val2,key)=>{ console.log(val2) arr.push(val2.message) if(count===json.data.length) { let reverse = [...arr].reverse() setMessages(reverse) } count++; }) } else if(!json.status) alert(json.msg) setLoading(false); //setdisTime({distance:json.data.distance,time:json.data.time_taken}) }) } } }) } let interval = setInterval(()=>getDoc(),4000) return () => { isMounted = false; clearInterval(interval); }; // cleanup toggles value, if unmounted }, []) const onSend = useCallback((messages = [],userid) => { console.log(userid) if(userid){ console.log(messages[0]) setMessages(previousMessages => GiftedChat.append(previousMessages, messages)) let data = { method: 'POST', //credentials: 'same-origin', //mode: 'same-origin', body: JSON.stringify({ "channel_id":'channel_id', "userId":userid, "message":messages[0], }), headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', //'X-CSRFToken': cookie.load('csrftoken') } } fetch('http://localhost:3000/api/add_message',data) .then((response) => response.json()) .then(async (json) => { console.log(json); //return; }) } }, []) if (loading) { return (<View><Spinner visible={loading} /></View>); } return ( <GiftedChat messages={messages} onSend={messages => onSend(messages,user._id)} user={{ _id: user._id, name: user.name, }} /> ) } /*avatar: auth?.currentUser?.photoURL*/ export default NewChat |
3. Set up nodejs code for save data with rest API
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
var MongoClient = require('mongodb').MongoClient; var url = "mongodb://localhost:27017/"; // add chat data exports.addchat = (req, res) => { // Save to MySQL database MongoClient.connect(url, async function(err, db) { if (err) throw err; var dbo = db.db("database_name"); var d = new Date(); var ctime = d.getTime(); var myobj = { channel_id: req.body.channel_id,userId: req.body.userId, message: message, timestamp: ctime }; await dbo.collection("chat").insertOne(myobj, function(err, res) { if (err) throw err; db.close(); }); res.status(200).json({'msg': 'Your chat added successfully!!', 'status': 1}); }); }; |
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 |
//fetch chat data exports.chat = (req, res) => { // Save to MySQL database MongoClient.connect(url, async function(err, db) { if (err) throw err; var dbo = db.db("database_name"); console.log(req.params.id) var myobj = { 'channel_id': ObjectId(req.params.id) }; const document = await dbo.collection("chat").countDocuments(myobj) console.log(document) if(document>0){ await dbo.collection("chat").aggregate([ { $match : myobj }, { $lookup: { from: 'users', localField: 'userid', foreignField: '_id', as: 'user' } } ]).toArray(function(err, res2) { if (err) throw err; if(res2.length>0){ db.close(); setTimeout(() => { res.status(200).json(res2)}, 1000); }else res.status(200).json([]); //console.log(res2); return false; }); }else { res.status(200).json([]); } }); }; |
You can add this chat component in your react native project. this code may help you create chat application in easy manner.
Result:
Thank you for visiting 🙂