Laravel-echo and Pushy in React Native Chat app
faizullah
Posted on September 30, 2024
This documentation is for adding laravel-echo and Pushy in react native to build a chat app.
If we have app that is using laravel backend server and want to implement live chat app in react native than we have to use 4 packages.
Find the installation steps see the above links.
After the installation we have to initialise the Pusher with key and options. Fill the options values of your laravel server.
import Pusher from 'pusher-js';
import Echo from 'laravel-echo';
let res: any = await getConfig();
let token1 = res.token;
let config1 = res?.config;
let id = res?.id;
let options: any = {
cluster: 'mt1',
key: config1.pusher_app_key,
wsHost: config1?.pusher_host,
wsPort: config1?.pusher_port,
wssPort: config1?.pusher_port,
disableStats: true,
forceTLS: true,
enabledTransports: ['wss', 'ws'],
authEndpoint: endpoint1 + '/api/broadcasting/auth',
auth: {
headers: {
Authorization: 'Bearer ' + token1
}
}
};
let PusherClient = new Pusher(options.key, options);
const echo1: any = new Echo({
broadcaster: 'pusher',
client: PusherClient,
});
if (echo1) {
const userChannel1 = echo1.private(`messenger.user.${id}`);
userChannel1.listen('.new.message', (notification: any) =>
{
setNotification1(notification);
})
}
Make a method of below code and call it in useEffect on entry point after login.
Now you will be able to get live chat messages.
Now the problem is for display notification. If your app doesn't use in China than use Firebase otherwise Pushy/TencentCloud is good option. Pushy integration in react native is very easy from Firebase and TencentCloud , but only 100 devices are free.
import notifee from '@notifee/react-native';
Pushy.setNotificationListener(async (data: any) => {
let notificationTitle = data?.title || '';
let notificationText = data?.message || 'New notification';
const channelId = await notifee.createChannel({
id: 'default',
name: 'Default Channel',
sound: 'default',
});
await notifee.displayNotification({
title: notificationTitle,
body: notificationText,
android: {
channelId,
smallIcon: 'ic_launcher',
pressAction: {
id: 'default',
},
},
data: data
});
});
notifee.onBackgroundEvent(async () => { })
Pushy.listen();
Place the above code just after import statements and before const
App=()=>{} function in App.tsx.
notifee is used to handle notification click event when app is in background and foreground mode.
Conclusion
With these steps, we've successfully integrated React Native with laravel-echo. Now your app is equipped to leverage instant chat, notification click event in background and foreground.
Final Thoughts
By combining React Native's flexibility with laravel-echo , you've set the foundation for a live chat system, in mobile app. Keep experimenting, and let us know what you build!
Posted on September 30, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.