My client side is in React Native (android app). In my chat feature, the client listening to websocket event that alerts when new message incoming in the chat. When I get the message from the socket, I render the specific chat message component. In emulator everything work just fine and the component is rendering. When we install the APK on our devices, the chat doesn't render. I thought maybe there are disconnections from the socket, but it's stable, what can be the problem?
This is how I listening to the websocket message:
function socketService(token) {
return eventChannel(emitter => {
const socket = new WebSocket(`${path}`, null, {
headers: {
authorization: 'Bearer ' + token,
},
});
if (socket) {
socket.onopen = () => {
console.log('SOCKET CONNECTED');
};
socket.onmessage = event => {
console.log('New message');
return emitter({type: newMessageWaiting.type, payload: event.data});
}
};
socket.onclose = event => {
console.log(event);
alert('SOCKET CLOSED');
};
}
return () => {
console.log('SOCKET OFF');
};
});
}
export function* watchSocket() {
const token = yield select(getToken);
const requestChan = yield call(socketService, token);
try {
while (true) {
let data = yield take(requestChan);
if (data.type === refreshOnlineUsers.type) {
yield put(refreshOnlineUsers());
}
if (data.type === newMessageWaiting.type) {
let theirMessage = JSON.parse(data.payload);
yield put(newMessageWaiting());
yield put(addMessageToChat({myMessage: theirMessage}));
}
} catch (err) {
console.error(err);
}
}
This is how I render the chat component:
const messageWaiting = useSelector(state => state.chat.messageWaiting);
const dispatch = useDispatch();
const getMessages = async () => {
try {
const res = await axios.get(`${path}/chats/${myId}/${friendId}/0`, {
headers: {
Authorization: 'Bearer ' + verifyToken,
},
});
if (res.data.hasOwnProperty('msg')) {
dispatch(
setCurrentChat({
currChat: [],
}),
);
} else {
dispatch(
setCurrentChat({
currChat: res.data,
}),
);
}
} catch (error) {
console.error(error);
}
};
useEffect(() => {
alert('**1*');
getMessages();
alert('**2*');
}, [dispatch, messageWaiting]); //BUG - NOT RENDER ON-NEW-MESSAGE