socketcluster-client icon indicating copy to clipboard operation
socketcluster-client copied to clipboard

I got TypeError: Object is not async iterable error while trying to listen to message event in React Native app

Open paulosabayomi opened this issue 2 years ago • 2 comments

Hi I am working on a React Native app and I have setup socketcluster websocket and I was able to connect to it from the app because I exposed the port of the websocket running locally on my PC with ngrok, but when I tried to listen to message events from the socket I keep getting TypeError: Object is not async iterable error in the command line and the app could not get any message from the socket

this is the code for listening to message event according to the documentation

try {
      for await (let data of this.socket_channel) {
                console.log('listenForData::: I got data from socket:::', data);
       }            
} catch (error) {
            console.log('socket message conn err', error);            
}

the socket initialization

this.websocket_instance = new SocketCluster.create({
  hostname: 'x.tcp.xx.ngrok.io',
  port: xxxxx
})

this.socket_channel = this.websocket_instance.subscribe(channel_name)
        
await this.socket_channel.listener('subscribe').once()

this.socket_channel.transmitPublish('hello from mobile phone')

the websocket connects successfully but I can't subscribe to message event and I can't get message from the socket

please is there any other ways I can subscribe to message event from the websocket except from using the for await (let data of this.socket_channel) { way, please help

paulosabayomi avatar Jun 21 '23 03:06 paulosabayomi

Use this code to fix that issue in React Native:

  subscribe = async (channelName, handler = (data) => {}) => {
    if (!this.socketInstance?.isSubscribed(channelName)) {
      let channel = this.socketInstance?.subscribe(channelName);
      const iterator = channel[Symbol.asyncIterator]();

      let result = await iterator.next();
      while (!result.done) {
        handler(result.value);
        result = await iterator.next();
      }
    }
  };

kyunkakata avatar Oct 10 '24 10:10 kyunkakata

I faced exactly same issue and tried this solution. Works for me. Ijust replaced

for await (let data of defaultChannel) { console.log("Received data, data); }

with

const iterator = defaultChannelSymbol.asyncIterator;

let result = await iterator.next(); while (!result.done) { result = await iterator.next(); }

I dont get the difference. Why does it work ?

suryahota1 avatar May 27 '25 15:05 suryahota1