EPeak Daily

The right way to construct a buyer help stay chat widget with React

0 8


Stay chat is a buyer help technique with a confirmed file. It’s quick and environment friendly since one agent might help many purchasers without delay. Better of all, the faster you may reply buyer’s questions throughout the shopping for course of, the extra doubtless that individual is to purchase.

So, how do you combine a stay chat into your React software?

style="display:block; text-align:center;" data-ad-format="fluid" data-ad-layout="in-article" data-ad-client="ca-pub-4791668236379065" data-ad-slot="8840547438">

On this tutorial, I’m going to point out you how you can combine a stay chat characteristic into your React app with out the concern of sustaining your personal chat server and structure.

Right here’s a preview of what we’ll be constructing:

To energy our chat software, we’ll be utilizing CometChat Professional.

CometChat Professional is a strong communication API that allows you to add chat options to your software. With simple integrations and clear documentation, you’ll be capable to add a stay chat characteristic into your software with only a few traces of code, as you’ll quickly see. If you wish to observe alongside, you may create a free account right here.

Along with CometChat, we’ll use the next applied sciences:

I encourage you to observe alongside however in case you’d reasonably to skip forward to the code, you’ll find the whole code for this software on GitHub.

First issues first, create your CometChat app

To energy your chat software, you’ll be utilizing CometChat. Earlier than you may combine CometChat, nonetheless, you will need to first create a CometChat app.

To create a CometChat app, go to the CometChat dashboard (in case you don’t have a free CometChat account already now is an efficient time to enroll) and hit the + icon.

I known as my software “react-chat-widget” however you may name yours no matter you want.

We’ll have two varieties of customers hook up with our chat: Clients who open the chat widget and one help agent who will entry the chat and reply to inquiries from the dashboard. Customers are a basic idea in CometChat, which you’ll learn extra about right here.

As a result of we’ll doubtless have many purchasers, for every buyer who connects to our chat, we might want to dynamically create a CometChat person. Nevertheless, as a result of there’ll solely be one agent, we will create an “Agent” person prematurely from the dashboard.

To take action, click on Discover then head to the Customers tab. Right here, you may click on Create Person:

For the person ID, I wrote “ecommerce-agent” and for the identify, I wrote “Demo Agent”. I like to recommend you utilize the identical values in case you’re following alongside. In any case, pay attention to the person ID since you’ll have to reference it later.

Earlier than we transfer on from the dashboard and on to the code, we must always create a CometChat full entry key.

On the identical web page, click on the API Keys tab then Create API Key:

I known as my key “react-chat-api” but it surely doesn’t actually matter what you write right here.

Word your API key and app ID as a result of, just like the agent person ID, you’ll want them each later.

Organising Specific

Within the earlier step, we created a full entry key, which we will use to create CometChat customers dynamically. Whereas we might do that on the shopper, that may imply sharing our non-public full entry key in public, which is a no go.

To keep away from this drawback, we’ll create a easy Specific server that:

  1. Creates CometChat person utilizing the complete entry key
  2. Returns authentication tokens (extra on this later)
  3. Returns an inventory of CometChat customers, to be used later within the dashboard

Alright, let’s begin.

First, create a brand new empty listing in your Specific app and run `npm init -y`:

mkdir react-express-chat-widget
cd react-express-chat-widget
npm init -y

Subsequent, set up Specific and axios:

npm set up categorical axios

Then, in a file known as sever.js paste:

const categorical = require('categorical');
const axios = require('axios');
const app = categorical();

// enter CometChat Professional configurations right here
const appID = '{appID}';
const apiKey = '{apiKey}';
const agentUID = '{agentUID}';

const url = 'https://api.cometchat.com/v1';

const headers = {
'Content material-Kind': 'software/json',
appid: appID,
apikey: apiKey,
};

Within the above file, we:

  1. Retailer our software credentials and agent person ID, which we created earlier
  2. Outline the CometChat API url for handy entry
  3. Create a headers object with our appID and apiKey. We’ll ship this header with each request to CometChat

In the identical file, let’s now outline a path to deal with creating new CometChat customers.

With a purpose to create a brand new person, we have to ship a POST request with the UID and identify for the person.

On this tutorial, we’ll hard-code the identical identify for all clients — we’ll name each buyer “buyer” — however the UID needs to be distinctive. For the UID, we will use new Date().getTime() to generate a random ID.

Add the next code to server.js:

app.get('/api/create', (req, res) => {
// knowledge for brand new person
const knowledge = {
// you should use your personal logic to generate random UID and identify
// solely uid needs to be distinctive
uid: new Date().getTime(),
identify: 'buyer',
};
axios
.publish(`${url}/customers`, JSON.stringify(knowledge), {
headers,
})
.then(response => {
// person is created, fetch auth token
requestAuthToken(response.knowledge.knowledge.uid)
.then(token => {
console.log('Success:' + JSON.stringify(token));
// token is returned to shopper
res.json(token);
})
.catch(error => console.error('Error:', error));
})
.catch(error => console.error('Error:', error));
});

// this perform will fetch token
const requestAuthToken = uid => {
return new Promise((resolve, reject) => {
axios
.publish(`${url}/customers/${uid}/auth_tokens`, null, {
headers,
})
.then(response => {
console.log('New Auth Token:', response.knowledge);
resolve(response.knowledge.knowledge);
})
.catch(error => reject(error));
});
};

When this route known as, Specific will:

  • Ship a POST request to https://api.cometchat.com/v1/customers/ with the proper headers and details about the brand new person
  • Fetch an authentication token for the brand new person
  • And, lastly, return it to the caller

We additionally created a perform known as requestAuthToken to assist with fetching the authentication token.

Subsequent, in the identical file, let’s create an authentication route we will name to create tokens for returning customers:

//...

app.get('/api/auth', (req, res) => {
const uid = req.question.uid;
// you probably have your personal login technique, name it right here.
// then name CometChat for auth token
requestAuthToken(uid)
.then(token => {
console.log('Success:' + JSON.stringify(token));
res.json(token);
})
.catch(error => console.error('Error:', error));
});

//...

Lastly, let’s create a perform to return an inventory of customers, excluding the agent.

We’ll name this endpoint from the dashboard later to point out an inventory of customers the agent can speak with (after all, the agent doesn’t wish to speak to themselves, so we filter them from the record):

//...

app.get('/api/customers', (req, res) => {
axios
.get(`${url}/customers`, {
headers,
})
.then(response => {
const { knowledge } = response.knowledge;
const filterAgentData = knowledge.filter(knowledge => {
// filter agent out from the record of customers
return knowledge.uid !== agentUID;
});
res.json(filterAgentData);
})
.catch(error => console.error('Error:', error));
});

//...

On the very backside of server.js, run the server:

const PORT = course of.env.PORT || 5000;
app.pay attention(PORT, () => {
console.log(`Listening on port ${PORT}`);
});

In the event you’ve been following alongside, that is what server.js ought to seem like by now:

const categorical = require('categorical');
const axios = require('axios');
const app = categorical();

const appID = '{appID}';
const apiKey = '{apiKey}';
const agentUID = '{agentUID}';

const url = 'https://api.cometchat.com/v1';

const headers = {
'Content material-Kind': 'software/json',
appid: appID,
apikey: apiKey,
};

app.get('/api/create', (req, res) => {
const knowledge = {
uid: new Date().getTime(),
identify: 'buyer',
};
axios
.publish(`${url}/customers`, JSON.stringify(knowledge), {
headers,
})
.then(response => {
requestAuthToken(response.knowledge.knowledge.uid)
.then(token => {
console.log('Success:' + JSON.stringify(token));
res.json(token);
})
.catch(error => console.error('Error:', error));
})
.catch(error => console.error('Error:', error));
});

app.get('/api/auth', (req, res) => {
const uid = req.question.uid;
requestAuthToken(uid)
.then(token => {
console.log('Success:' + JSON.stringify(token));
res.json(token);
})
.catch(error => console.error('Error:', error));
});

const requestAuthToken = uid => {
return new Promise((resolve, reject) => {
axios
.publish(`${url}/customers/${uid}/auth_tokens`, null, {
headers,
})
.then(response => {
console.log('New Auth Token:', response.knowledge);
resolve(response.knowledge.knowledge);
})
.catch(error => reject(error));
});
};

app.get('/api/customers', (req, res) => {
axios
.get(`${url}/customers`, {
headers,
})
.then(response => {
const { knowledge } = response.knowledge;
const filterAgentData = knowledge.filter(knowledge => {
return knowledge.uid !== agentUID;
});
res.json(filterAgentData);
})
.catch(error => console.error('Error:', error));
});

const PORT = course of.env.PORT || 5000;
app.pay attention(PORT, () => {
console.log(`Listening on port ${PORT}`);
});

In a terminal window, run node server.js and look out for a message that claims “Listening on port 5000”. Now could be a superb time to check the end-points with curl or Postman however we’ll belief they work and transfer on to the shopper.

Organising the react app

Inside your listing, run npx create-react-app to scaffold a brand new React software:

npx create-react-app shopper

Your folder construction ought to seem like this:

|-- express-react-chat-widget
|-- package-lock.json
|-- package deal.json
|-- server.js
|-- shopper
|-- .gitignore
|-- package-lock.json
|-- package deal.json
|-- public
|-- src

Along with your React software in place, navigate to the shopper listing set up the next modules:

cd shopper
npm set up @cometchat-pro/chat react-chat-widget react-router-dom bootstrap react-md-spinner

Create React app is admittedly helpful to bootstrap a React app, but it surely additionally generates numerous information we don’t want (take a look at information, and so forth).

Earlier than we bounce into the code, take away the whole lot within the shopper/src listing – we’ll begin from scratch.

To start, create a config.js file along with your app ID and agent UID inside:

// shopper/src/config.js
const config = {
appID: '{appID}',
agentUID: '{agentUID}',
}
export default config;

This can be a little bit of boilerplate we will use to reference our CometChat credentials from anyplace.

Whereas we’re coping with boilerplate, let’s additionally take this chance to create an index.css file:

physique {
margin: 0;
padding: 0;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen",
"Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue",
sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}

code {
font-family: source-code-pro, Menlo, Monaco, Consolas, "Courier New", monospace;
}

.message {
overflow: hidden;
}

.balon1 {
float: proper;
background: #35cce6;
border-radius: 10px;
}

.balon2 {
float: left;
background: #f4f7f9;
border-radius: 10px;
}

We are going to reference this later from the dashboard.

Now, in a file known as index.js paste the next:

import React from 'react';
import ReactDOM from 'react-dom';
import 'bootstrap/dist/css/bootstrap.css';
import './index.css';
import App from './App';
import { CometChat } from '@cometchat-pro/chat';
import config from './config';

CometChat.init(config.appID)
ReactDOM.render(<App />, doc.getElementById('root'));

Right here, we import Bootstrap, CometChat, and the config file we simply created earlier than initialising CometChat and rendering our App.

In the event you’re following alongside, you’ll have observed we haven’t outlined App but – let’s try this now.

In a file known as App.js:

import React from 'react';
import { BrowserRouter as Router, Route, Hyperlink } from 'react-router-dom';
import Consumer from './Consumer';
import Agent from './Agent';

const App = () => {
return (
<Router>
<React.Fragment>
<ul>
<li>
<Hyperlink to='/'>Consumer House</Hyperlink>
</li>
<li>
<Hyperlink to='/agent'>Agent Dashboard</Hyperlink>
</li>
</ul>
<hr />
<Route actual path='/' part={Consumer} />
<Route path='/agent' part={Agent} />
</React.Fragment>
</Router>
);
}
export default App;

Right here, we outline two routes:

  • The / or "Buyer residence" route for the client to talk with the agent
  • And the /agent or "Agent Dashboard" route for fast and handy entry to the dashboard

Let’s deal with the customer-facing part first. We’ll name this the shopper part.

Creating the shopper part

Our shopper part could have two important tasks:

  1. Create a brand new CometChat person by means of our Specific server when a buyer first connects
  2. Ship and obtain messages in real-time.

Create a file known as Consumer.js and paste the next:

// Consumer.js

import React, {Element} from 'react';
import { Widget, addResponseMessage, addUserMessage, dropMessages } from 'react-chat-widget';
import { CometChat } from '@cometchat-pro/chat';
import config from './config';
import 'react-chat-widget/lib/kinds.css';

const agentUID = config.agentUID;
const CUSTOMER_MESSAGE_LISTENER_KEY = "client-listener";
const restrict = 30;

class Consumer extends Element {
componentDidMount() {
addResponseMessage('Welcome to our retailer!');
addResponseMessage('Are you in search of something particularly?');
}

render() {
return (
<div className='App'>
<Widget
handleNewUserMessage={this.handleNewUserMessage}
title='My E-commerce Stay Chat'
subtitle='Prepared that will help you'
/>
</div>
);
}

createUser = async () => {
const response = await fetch(`/api/create`)
const consequence = await response.json()
return consequence;
}

handleNewUserMessage = newMessage => {
console.log(`New message incoming! ${newMessage}`);
var textMessage = new CometChat.TextMessage(
agentUID,
newMessage,
CometChat.MESSAGE_TYPE.TEXT,
CometChat.RECEIVER_TYPE.USER
);
let uid = localStorage.getItem("cc-uid");
if (uid === null) {
// no uid, create person
this.createUser().then(
consequence => {
console.log('auth token fetched', consequence);
localStorage.setItem("cc-uid",consequence.uid)
// do login
CometChat.login(consequence.authToken)
.then(person => {
console.log("Login efficiently:", { person });
CometChat.sendMessage(textMessage).then(
message => {
console.log('Message despatched efficiently:', message);
},
error => {
console.log('Message sending failed with error:', error);
}
);
// create listener
CometChat.addMessageListener(
CUSTOMER_MESSAGE_LISTENER_KEY,
new CometChat.MessageListener({
onTextMessageReceived: message => {
console.log("Incoming Message Log", { message });
addResponseMessage(message.textual content);
}
})
);
})
},
error => {
console.log('Initialization failed with error:', error);
})
} else {
// we have now uid, do ship
CometChat.sendMessage(textMessage).then(
message => {
console.log('Message despatched efficiently:', message);
},
error => {
console.log('Message sending failed with error:', error);
}
);
}
};
componentWillUnmount() {
CometChat.removeMessageListener(CUSTOMER_MESSAGE_LISTENER_KEY);
CometChat.logout();
dropMessages();
}
}

export default Consumer;

Woah, that’s numerous new code. Let’s break it down.

The render perform is straightforward sufficient, it primarily boils right down to rendering the react-chat-widget.

A lot of the code is devoted to dealing with new message despatched by the client within the perform known as handleNewUserMessage.

In a nutshell, we first examine to see if buyer UID exists in localStorage. If it does, we’ll use this UID to log the person in and ship messages. In any other case, we name createUser() and use the returned worth to login. This createUser perform calls the endpoint we outlined earlier within the tutorial.

Lastly, in a React lifecycle perform known as componentWillUnmount, we bear in mind to take away the message listener.

Earlier than transferring on, right here’s slightly tip: Within the above code, reasonably than typing server url and port ("localhost:5000/customers" or one thing like that) in our front-end, we will as an alternative add a proxy choice to package deal.json. It will permit us to write down /customers" as an alternative of //localhost:5000/customers":

"browserslist": [
">0.2%",
"not useless",
"not ie <= 11",
"not op_mini all"
],
"proxy": "http://localhost:5000"

Here’s what the appliance ought to seem like:

As you may see, you may ship and obtain messages, but when we refresh our web page, the chat messages will all disappear and that’s no good.

To unravel this challenge, we’ll setup the componentDidMount technique to search for buyer UID in localStorage, in order that when clients refresh the web page, they’ll proceed chatting from the place they left off.

As soon as discovered, we’ll use this UID to provoke a series of strategies to login, fetch earlier messages and create listener for incoming messages.

componentDidMount() {
addResponseMessage('Welcome to our retailer!');
addResponseMessage('Are you in search of something particularly?');

let uid = localStorage.getItem("cc-uid");
// examine for uid, if exist then get auth token
if ( uid !== null) {
this.fetchAuthToken(uid).then(
consequence => {
console.log('auth token fetched', consequence);
// SDK login
CometChat.login(consequence.authToken)
.then( person => {
console.log("Login efficiently:", { person });
// take heed to incoming message and fetch earlier messages
this.createMessageListener();
this.fetchPreviousMessages();

})
},
error => {
console.log('Initialization failed with error:', error);
}
);
}
}

// The capabilities used above

fetchAuthToken = async uid => {
const response = await fetch(`/api/auth?uid=${uid}`)
const consequence = await response.json()
return consequence;
}

createMessageListener = () => {
CometChat.addMessageListener(
CUSTOMER_MESSAGE_LISTENER_KEY,
new CometChat.MessageListener({
onTextMessageReceived: message => {
console.log("Incoming Message Log", { message });
addResponseMessage(message.textual content);
}
})
);
}

fetchPreviousMessages = () => {
var messagesRequest = new CometChat.MessagesRequestBuilder()
.setUID(agentUID)
.setLimit(restrict)
.construct();
messagesRequest.fetchPrevious().then(
messages => {
console.log("Message record fetched:", messages);
// add messages to the widget chat bubbles
messages.forEach( message => {
if(message.receiver !== agentUID){
addResponseMessage(message.textual content);
} else {
addUserMessage(message.textual content)
}
});
},
error => {
console.log("Message fetching failed with error:", error);
}
);
}

Now if we refresh our web page, the app will attempt to login to CometChat and fetch earlier messages routinely by in search of our buyer UID from the localStorage. Great things!

There’s nonetheless a small drawback, although. Because it stands proper now, there’s nonetheless no means for an agent to answer to buyer’s messages.

We are going to resolve this drawback by constructing the agent dashboard, the place our agent can view and reply chat messages from clients.

We’re completed with the Consumer.js file, so you may seize a espresso earlier than transferring on to code the Agent.js file ☕

Creating the agent part

The principle perform of the agent dashboard is to seize all clients from CometChat Professional and show any incoming message from new buyer into the client record chat for brokers to click on on and reply. The core performance is similar to the shopper:

With CometChat, you would simply create a number of brokers however to maintain issues easy and keep away from person administration, we have now just one agent, which we created earlier.

Create a part known as Agent.js and set the preliminary state:

import React, {Element} from 'react';
import {CometChat} from '@cometchat-pro/chat';
import MDSpinner from "react-md-spinner";
import config from './config';

const agentUID = config.agentUID;
const AGENT_MESSAGE_LISTENER_KEY = 'agent-listener'
const restrict = 30;

class Agent extends Element {
state = {
clients: [],
selectedCustomer: '',
chat: [],
chatIsLoading: false,
customerIsLoading:true
}
}

In the identical file, create a componentDidMount technique:

componentDidMount(){
this.fetchAuthToken(agentUID).then(
authToken => {
console.log('auth token fetched', authToken);
CometChat.login(authToken)
.then( person => {
console.log("Login efficiently:", { person });
// after login, fetch all customers
// put them into buyer state
this.fetchUsers().then(consequence => {
this.setState({
clients: consequence,
customerIsLoading: false
})
});

CometChat.addMessageListener(
AGENT_MESSAGE_LISTENER_KEY,
new CometChat.MessageListener({
onTextMessageReceived: message => {
let {clients, selectedCustomer, chat} = this.state;
console.log("Incoming Message Log", { message });
// examine incoming message
// if from the identical buyer agent is at the moment chatting
// push a brand new chat merchandise into chat state
if(selectedCustomer === message.sender.uid){
chat.push(message);
this.setState({
chat
})
} else {
// if new buyer, push a brand new buyer into buyer state
let aRegisteredCustomer = clients.filter( buyer => {
return buyer.uid === message.sender.uid });
if(!aRegisteredCustomer.size){
clients.push(message.sender)
this.setState({
clients
})
}
}
}
})
);
})
},
error => {
console.log('Initialization failed with error:', error);
}
);
}

fetchUsers = async () => {
const response = await fetch(`/api/customers`)
const consequence = await response.json()
return consequence;
}

There’s loads taking place within the above code, right here’s a rundown that will help you perceive:

  1. First, we routinely login our agent and fetch all customers for the agent to talk with from the server
  2. Subsequent, we create an incoming message listener. Each time a message is acquired within the chosen dialog, we push it to the chat state which, in flip, updates the UI
  3. If the incoming message is just not from the at the moment chosen dialog, we examine to see if the brand new message is from registered buyer. If not, we push that new buyer to the client state.

You’ll most likely recognise the Specific API we create to get an inventory of registered customers. We use this to populate the record of customers on the left-hand-side of the dashboard. We are going to place the record to the left-hand-side utilizing a mixture of Bootstrap lessons and the index.css file we outlined earlier.

Subsequent, let’s create the render perform. It should render a dialog interface, styled with Bootstrap. To make the code simpler to observe, we’ll separate CustomerList and ChatBox into their very own elements, which you’ll outline in the identical file:

render() {
return(
<div className='container-fluid'>
<div className='row'>
<div className='col-md-2'></div>
<div className="col-md-Eight h-100pr border rounded">
<div className='row'>
<div className='col-lg-Four col-xs-12 bg-light' model={{ peak: 658 }}>
<div className='row p-3'><h2>Buyer Checklist</h2></div>
<div className='row ml-Zero mr-Zero h-75 bg-white border rounded'
model={{ peak: '100%', overflow:'auto' }}>
{/* The CustomerList part */}
<CustomerList {...this.state} selectCustomer={this.selectCustomer}/>
</div>
</div>
<div className='col-lg-Eight col-xs-12 bg-light' model={{ peak: 658 }}>
<div className='row p-Three bg-white'>
<h2>Who you gonna chat with?</h2>
</div>
<div className='row pt-5 bg-white'
model={{ peak: 530, overflow:'auto' }}>
{/* The ChatBox part */}
<ChatBox {...this.state} />
</div>
<div className="row bg-light" model={{ backside: 0, width: '100%' }}>
<kind className="row m-Zero p-Zero w-100" onSubmit={this.handleSubmit}>

<div className="col-9 m-Zero p-1">
<enter id="textual content"
className="mw-100 border rounded form-control"
sort="textual content"
identify="textual content"
ref="message"
placeholder="Kind a message..."/>
</div>
<div className="col-Three m-Zero p-1">
<button className="btn btn-outline-secondary rounded border w-100"
title="Ship"
model={{ paddingRight: 16 }}>Ship</button>
</div>
</kind>
</div>
</div>
</div>
</div>
</div>
</div>
)
}

Chatbox part:

class ChatBox extends Element {
render(){
const {chat, chatIsLoading} = this.props;
if (chatIsLoading) {
return (
<div className='col-xl-12 my-auto text-center'>
<MDSpinner dimension='72'/>
</div>
)
}
else {
// easy mapping of array from props
return (
<div className='col-xl-12'>
{
chat
.map(chat =>
<div key={chat.id} className="message">
<div className={
`${chat.receiver !== agentUID ? 'balon1': 'balon2'} p-Three m-1`
}>
{chat.textual content}
</div>
</div>)
}
</div>
)
}
}
}

CustomerList part:

class CustomerList extends Element {
render(){
const {clients, customerIsLoading, selectedCustomer} = this.props;
if (customerIsLoading) {
return (
<div className='col-xl-12 my-auto text-center'>
<MDSpinner dimension='72'/>
</div>
)
}
else {
// easy mapping of array from props
return (
<ul className="list-group list-group-flush w-100">
{
clients
.map(buyer =>
<li
key={buyer.uid}
className={
`list-group-item ${buyer.uid === selectedCustomer ? 'energetic':''}`
}
onClick={ () => this.props.selectCustomer(buyer.uid) }>
{buyer.identify}
</li>)
}
</ul>
)
}
}
}

That makes up the muse for our UI, however we nonetheless can’t ship messages.

To ship messages, we have now to create a handler for when the agent submits a brand new message. The right way to ship messages must be acquainted to you now as a result of we’ll make the the identical sendMessage name that we made within the Consumer part as effectively.

handleSubmit = occasion => {
occasion.preventDefault();
let message = this.refs.message.worth;
var textMessage = new CometChat.TextMessage(
this.state.selectedCustomer,
message,
CometChat.MESSAGE_TYPE.TEXT,
CometChat.RECEIVER_TYPE.USER
);

CometChat.sendMessage(textMessage).then(
message => {
let {chat} = this.state;
console.log('Message despatched efficiently:', message);
chat.push(message);
this.setState({
chat
})
},
error => {
console.log('Message sending failed with error:', error);
}
);
this.refs.message.worth='';
}

We’ll additionally wish to allow the agent to see historic messages like we did for the client:

selectCustomer = uid => {
this.setState({
selectedCustomer: uid
}, ()=> {this.fetchPreviousMessage(uid)})
}

fetchPreviousMessage = uid => {
this.setState({
hat: [],
chatIsLoading: true
}, () => {
var messagesRequest = new CometChat.MessagesRequestBuilder()
.setUID(uid)
.setLimit(restrict)
.construct();
messagesRequest.fetchPrevious().then(
messages => {
console.log("Message record fetched:", messages);
this.setState({
chat: messages,
chatIsLoading: false
})
},
error => {
console.log("Message fetching failed with error:", error);
}
);
});
}

Bear in mind to take away the message listener when the part unmounts:

componentWillUnmount(){
CometChat.removeMessageListener(AGENT_MESSAGE_LISTENER_KEY);
CometChat.logout();
}

In case you have any hassle, you may reference the whole Agent file right here on GitHub.

Take a look at the ultimate product:

In the event you’re questioning the place these superhero customers got here from, they’re routinely created by CometChat Professional if you create a brand new app. Don’t overlook to delete them earlier than utilizing the app in manufacturing.

Now each the help agent and your clients are prepared to talk with one another. You’ll be able to open Consumer House and Agent Dashboard in separate home windows and take a look at it out.

Congratulations!

Conclusion

We’ve made our very personal stay chat widget for React software, and it took no time in any respect! Certainly, CometChat Professional allows you to ship and obtain message by solely writing a number of traces of code. You don’t have to take care of creating your personal chat server and structure. It additionally has extra capabilities than simply making a chat widget.

In the event you needed to develop this software, strive enabling clients to ship media messages with CometChat.

P.S: In the event you’re struggling to study React, You would possibly discover React Distilled an important assist. Test it out right here!



Supply hyperlink

Leave A Reply

Hey there!

Sign in

Forgot password?
Close
of

Processing files…