lukeed / sockette

The cutest little WebSocket wrapper! 🧦
MIT License
2.45k stars 81 forks source link

When the state is changed, I would like to close and reconnect using the new state. How do I do that? #35

Closed abdu997 closed 6 years ago

abdu997 commented 6 years ago

Hello,

I would like to close a socket connection when my this.state.chartSymbol changes, and reconnect with a new WS url using the new this.state.chartSymbol. The image attached is what I have so far, I know its wrong, but I dont know why.

Thank you

screen shot 2018-09-11 at 10 52 46 pm
lukeed commented 6 years ago

Hey,

When you call reconnect (which is a function btw), it reconnects to the existing / current URL. You need to recreate a new ws entirely by calling binanceSocket (or extracting the Sockette portion to a helper function).

abdu997 commented 6 years ago

binanceSocket is initially called in componentWillMount. Even when symbolChanger calls binanceSocket(), it maintains the old connection and the new connection. How do I stop the old connection?

screen shot 2018-09-11 at 11 48 29 pm
lukeed commented 6 years ago

This should do the trick for you 👍

Closing as it's not related to Sockette anymore, but lemme know how it goes~!

class Foobar extends Component {
    state = {
        symbol: ''
    };

    binanceSocket() {
        this.ws = new Sockette(`ws://.../ws/${this.state.symbol}@kline`, {
            // ...
        });
    }

    componentWillMount() {
        this.binanceSocket();
        // now `this.ws` exists
    }

    // You can also do this in:
    // - componentWillReceiveProps
    // - // etc, depends on your app
    componentDidUpdate(_, prev) {
        let now = this.state;
        if (prev.symbol !== now.symbol) {
            // We now have a NEW symbol; update the socket
            this.ws.close(); // graceful shutdown of old socket
            this.binanceSocket(); // NEW websocket is now created
        }
    }
}