I am trying to build a chat app and to produce realtime effect, I'm using socket.io
, I developed my server in node/express and it's working perfect, but the problem is in react-native side, as I'm not able to render the messages when the socket.on
is used (even though I'm doing it in correct way, I entered the correct dependency in the useEffect
). Below is some of the code from my app, and I will confirm that some parts are working fine, something is wrong only just in the useEffect
dependencies list.
Server side logic to listen/send message to target client ids:
socket.on('sendMessage', ({senderId, receiverId, text}) => {
console.log(text); // getting the output as expected here.
const user = Utility.getUser(users, receiverId);
io.to(user.socketId).emit('getMessage', {
senderId,
text,
});
});
Client side / React Native side:
const socket = useRef();
const [arrivalMessage, setArrivalMessage] = useState(null);
useEffect(() => {
// connect to server/api link
socket.current = io('...', {
transports: ['websocket'],
});
}, []);
useEffect(() => {
socket.current.on('getMessage', data => {
console.log('getmessages: ',data);
setArrivalMessage({
// matchId: matchId,
senderId: data.senderId,
text: data.text,
createdAt: Date.now(),
updatedAt: Date.now(),
});
});
// SOMETHING IS WRONG HERE, as this useEffect block is not being executed even though I have mentioned "socket" in my dependency list.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [socket]);
useEffect(() => {
// ensures we don't get any other user's msg
arrivalMessage &&
match.includes(arrivalMessage.senderId) &&
setMessages((prev) => [...prev, arrivalMessage]);
}, [arrivalMessage, match]);
So, something is wrong in the 2nd useEffect
as this useEffect block is not being executed even though I have mentioned "socket" in my dependency list, and hence the chatlist is not updated.
Also, there are no error logs in console so it adds more difficulty to debug...
I would really appreciate if someone point out what I'm doing wrong!
CodePudding user response:
You cannot use useRef
for the socket instance... mutating reference doesn't re-render content of the component therefore it doesn't trigger the useEffect
Here is an example how to use sockets in hook
export function useSocket(
url = process.env.NEXT_PUBLIC_API_URL /* default URL */
) {
const [socket, setSocket] = useState<SocketType>(null)
useEffect(() => {
const io: SocketType = SocketClient(url).connect()
setSocket(io)
return () => {
socket?.disconnect()
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
return socket
}
export function useSocketEvent(
socket: SocketType,
event: keyof SocketListenEventMap,
callback: (...args: unknown[]) => void
) {
useEffect(() => {
if (!socket) {
return
}
socket.on(event, callback)
return () => {
socket.off(event, callback)
}
}, [callback, event, socket])
return socket
}
export function useMessagesSocket() {
const [arrivalMessage, setArrivalMessage] = useState(null)
const socket = useSocket(/* URL */)
useSocketEvent(socket, 'getMessages', (data) =>
setArrivalMessage({
//...
})
)
}