Answer the question
In order to leave comments, you need to log in
How to translate a class into a functional component?
I made a messenger on sockets, but the whole project was created on functional components. Since there is no information on the Internet specifically about sockets, I left this file as a class. But perfectionism hits you in the head.
I have problems in insatnce, getInstance, construcor. And the fact is that I call some functions from the outside through the instance.
Can you help guide me to the right transformation? In no case do not ask to be worn out and help completely.
Do I understand correctly that it is possible to store variables and a constructor in useState. And the rest to make simple functions?
class WebSocketService {
static instance = null;
callbacks = {};
static getInstance() {
if (!WebSocketService.instance) {
WebSocketService.instance = new WebSocketService();
}
return WebSocketService.instance;
}
constructor() {
this.socketRef = null;
}
connect(chatUrl) {
const path = `ws://127.0.0.1:8000/ws/chat/${chatUrl}/`;
this.socketRef = new WebSocket(path);
this.socketRef.onopen = () => {
console.log('WebSocket open');
};
this.socketRef.onmessage = e => {
this.socketNewMessage(e.data);
};
this.socketRef.onerror = e => {
console.log(e.message);
};
this.socketRef.onclose = () => {
console.log('WebSocket closed');
// this.connect(chatUrl);
};
}
disconnect() {
this.socketRef.close();
}
socketNewMessage(data) {
const parsedData = JSON.parse(data);
const { command } = parsedData;
if (Object.keys(this.callbacks).length === 0) {
return;
}
if (command === 'messages') {
this.callbacks[command](parsedData.messages);
}
if (command === 'new_message') {
this.callbacks[command](parsedData.message);
}
}
leaveChat(userId, chatId) {
this.sendMessage({
command: 'leave',
id: userId,
chatId,
});
}
addCallbacks(messagesCallback, newMessageCallback) {
this.callbacks.messages = messagesCallback;
this.callbacks.new_message = newMessageCallback;
}
sendMessage(data) {
try {
this.socketRef.send(JSON.stringify({ ...data }));
} catch (err) {
console.log(err.message);
}
}
state() {
return this.socketRef.readyState;
}
}
const WebSocketInstance = WebSocketService.getInstance();
export default WebSocketInstance;
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question