This documentation is for addinglaravel-echo andPushy 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 theinstallation steps see the above links.
After the installation we have to initialise thePusher withkey andoptions. Fill the optionsvalues of your laravel server.
import Pusher from 'pusher-js';
import Echo from 'laravel-echo';
letres:any=awaitgetConfig();lettoken1=res.token;letconfig1=res?.config;letid=res?.id;letoptions: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}}};letPusherClient=newPusher(options.key,options);constecho1:any=newEcho({broadcaster:'pusher',client:PusherClient,});if(echo1){constuserChannel1=echo1.private(`messenger.user.${id}`);userChannel1.listen('.new.message',(notification:any)=>{setNotification1(notification);})}
Make a method of below code and call it inuseEffect 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 inChina than useFirebase otherwisePushy/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)=>{letnotificationTitle=data?.title||'';letnotificationText=data?.message||'Newnotification';constchannelId=awaitnotifee.createChannel({id:'default',name:'DefaultChannel',sound:'default',});awaitnotifee.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 withlaravel-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!
Top comments(0)
For further actions, you may consider blocking this person and/orreporting abuse