IrfanAnwar
IrfanAnwar

Reputation: 79

Pubnub sending messages multiple times

I am using ReactJs to build a chat application with pubnub. The issue is my first message is sent 1 time, second is send twice and third is sent 3 times. What could be wrong, Here is my code. Do I need to unsubscribe at some point? The message is not just shown multiple times, it is actually sent.

class App extends Component {
    constructor(props) {
        super(props);
        this.pubnub = new PubNub({
            publishKey: 'demo',
            subscribeKey: 'demo',
        });
        this.sendMessage = this.sendMessage.bind(this);

    }
    sendMessage() {
        this.pubnub.publish({
            channel: "simple-chat",
            message: {
                text: this.state.currentMesage,
                sender: this.pubnub.getUUID()
            }
        });

        this.setState({
            currentMesage: ''
        });

        this.pubnub.subscribe({
            channels: ['simple-chat'],
            withPresence: true
        });
        this.pubnub.addListener({
            message: (evt) => {
                console.log('you have got a message:' + JSON.stringify(evt));
                this.state.messages.push({
                    text: evt.message.text
                })
                this.setState({
                    messages: this.state.messages
                });
            }
        });
    }

export default App;

Upvotes: 1

Views: 1334

Answers (1)

Avi Ivgi
Avi Ivgi

Reputation: 69

I believe that it's not a duplication of publish. I think that you are 're-subscribing' to the same channel over and over again... while publishing 'again and again', so with every new subscribe you are receiving all of the messages that were published to that channel (like History)

So, 1st publish->subscribe-> 1 message 2nd publish->subscribe-> 2 messages 3rd publish->subscribe-> 3 messages And so on...

  1. Your PubNub init should be global and/or better management of the Subscribe/Publish calls.
  2. Please use the UUID and set it with a static value

Best, Avi.

Upvotes: 4

Related Questions