'django websocket cannot send data to client after receiving it

class WSTestView(WebsocketConsumer):
    def connect(self):
        self.accept();

        self.send(json.dumps({'status': 'sent'})) # client receives this
    
    def receive(self, text_data=None, bytes_data=None):
        notifications = Notification.objects.filter(receiver=text_data) # receives user id
        serializer = NotificationSerializer(notifications, many=True).data

        self.send(serializer) # client does not receives this

Frontend

// ...
useEffect(() => {
    socket.onmessage = (e) => { console.log(e.data) }
  }, [])
// ...

I've just started with django-channels and am working on a consumer that sends the user's notifications when it receives the user's id but on the frontend the onmessage event does not receive anything, how can I fix this and is there a better way that I can implement this?



Solution 1:[1]

It's probably your front end and not django-channels if you're able to connect to it. The most probable reason is that your onmessage binds after, because of the componenDidMount/useEffect, the server has already sent the message.

Try just as a test, to rule that out. To put the

socket.onmessage = (e) => { console.log(e.data) }

Right after the new WebSocket.... Let me know if that prints something in the console. Another way to test/isolate it is with an online WebSocket tester like this https://www.lddgo.net/en/network/websocket

Solution 2:[2]

class WSTestView(WebsocketConsumer):
    def connect(self):
        self.accept();

        self.send(json.dumps({'status': 'sent'}))
    
    def receive(self, text_data=None, bytes_data=None):
        notifications = Notification.objects.filter(receiver=text_data) # receives user id
        serializer = NotificationSerializer(notifications, many=True).data

        self.send(json.dumps(serializer)) # <-------
  1. Had to convert the serialized data into a JSON string.

Frontend

useEffect(() => {
    socket.onmessage = (e) => { console.log(e.data) }
  }, [socket]) // <-------
  1. Had to put the socket variable into the dependency array

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 smerkd
Solution 2 Lun