kesha-antonov/react-native-action-cable

App is connecting to action cable multiple times

muhsin-k opened this issue · 10 comments

ActionCableConnector.js


import { ActionCable, Cable } from '@kesha-antonov/react-native-action-cable';
import { WEB_SOCKET_URL } from '../constants/url';

const connectActionCable = ActionCable.createConsumer(WEB_SOCKET_URL);

const cable = new Cable({});

import { getPubSubToken } from './AuthHelper';

import {
  addConversation,
  addMessageToConversation,
} from '../actions/conversation';

import { store } from '../store';

class ActionCableConnector {
  constructor(pubSubToken) {
    const channel = cable.setChannel(
      'RoomChannel',
      connectActionCable.subscriptions.create({
        channel: 'RoomChannel',
        pubsub_token: pubSubToken,
      }),
    );

    channel.on('received', this.onReceived);

    this.events = {
      'messageCreated': this.onMessageCreated,
    };
  }

  onReceived = ({ event, data } = {}) => {
  
    if (this.events[event] && typeof this.events[event] === 'function') {
      this.events[event](data);
    }
  };

  onMessageCreated = message => {
    store.dispatch(addMessageToConversation({ message }));
  };


}

export async function initActionCable() {
  const pubSubToken = await getPubSubToken();

  const actionCable = new ActionCableConnector(pubSubToken);
  return actionCable;
}

Root Component

import React, { Component } from 'react';
import { initActionCable } from '../../helpers/ActionCable';

class ConversationList extends Component {

  componentDidMount = () => {
    initActionCable();
  };
  render = () => {
    return (
      <Layout>
      </Layout>
    );
  };
}

export default ConversationList;

The connection to action cable is working here. But the problem is that whenever I tried to restart the app, It got connected to action cable again. So multiple events are firing. Is there any way to check the connection is already established or not?

@kesha-antonov Could you please help me with this?

Hi!
I need to take a look

Did you try disconnect on unmount?

Did you try to call

connectActionCable.disconnect()

on unmount?

And also to unsubscribe from all channels?

Yes

@muhzi4u Did you find a solution for this?

@cdesch No. I couldn't. Are you facing the same issue?

@muhzi4u

...whenever I tried to restart the app...
Is it related to Fast Refresh?

@kesha-antonov It is happening production version too.

@muhsin-k Did you ever solve this? I am having the same issue right now. Local Development is fine, production I get every message multiple times.