Chat Application

import ‘react-native-get-random-values’;
import AsyncStorage from ‘@react-native-async-storage/async-storage’;
import Echo from ‘laravel-echo’;
import Pusher from ‘pusher-js/react-native’;

let echoInstance = null;

export const initEcho = async () => { // ✅ async function
if (echoInstance) return echoInstance;

try {
const userData = await AsyncStorage.getItem(‘userdata’);
if (!userData) {
console.log(‘User data not found’);
return null;
}

const tokenData = JSON.parse(userData);
const token = tokenData?.data?.token;
// alert(token)
if (!token) {
console.log(‘Token not found in user data’);
return null;
}

// Initialize Pusher client pointing to your self-hosted Reverb server
const pusher = new Pusher(‘vubkg9ccrgssnkjt7w6d’, {
wsHost: ‘digitalfarmer.cloud’,
wsPort: 80,
wssPort: 443,
forceTLS: true,
encrypted: true,
wsPath: ‘/app/vubkg9ccrgssnkjt7w6d’,
enabledTransports: [‘ws’, ‘wss’],
disableStats: true,
cluster: ,
authEndpoint: ‘https://digitalfarmer.cloud/api/broadcasting/auth’,
});

// Initialize Echo with auth headers
echoInstance = new Echo({
broadcaster: ‘pusher’,
client: pusher,
auth: {
headers: {
Authorization: `Bearer ${token}`, // 🔑 dynamic token
Accept: ‘application/json’,
},
},
});

return echoInstance;
} catch (error) {
console.error(‘Error initializing Echo:’, error);
return null;
}
};
//Call inside chat

useEffect(() => {
const setupEcho = async () => {
const echo = await initEcho();
if (!echo) return;

const channel = echo.private(`chat.${chatId}`);
console.log(‘✅ CHANNEL’, channel);

// 🔹 optional: monitor connection
// const pusher = echo.connector?.pusher;
// if (pusher) {
// console.log(‘🔍 CONNECTION STATE:’, pusher);

// pusher.connection.bind(‘state_change’, s =>
// console.log(‘🔄 STATE CHANGE’, s)
// );
// pusher.connection.bind(‘connected’, () =>
// console.log(‘✅ WS CONNECTED’)
// );
// pusher.connection.bind(‘disconnected’, () =>
// console.log(‘⚠️ WS DISCONNECTED’)
// );
// pusher.connection.bind(‘error’, err =>
// console.log(‘❌ WS ERROR’, err)
// );
// }
// else{
// console.log(“Pusher not found”)
// }
channel.subscribed(() => {
console.log(‘✅ SUBSCRIBED’);
});

channel.error(err => {
console.log(‘❌ CHANNEL ERROR’, err);
});

channel.listen(‘.MessageSent’, e => {
console.log(‘🔥 MESSAGE RECEIVED’, e);
});

};

setupEcho();

return () => {
initEcho().then(echo => {
if (echo) echo.leave(`chat.${chatId}`);
});
};
}, [chatId]);

Scroll to Top