Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
abdu997 opened this issue Sep 12, 2018 · 3 comments
Labels

Comments

@abdu997
Copy link

abdu997 commented Sep 12, 2018

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
Copy link
Owner

lukeed commented Sep 12, 2018

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
Copy link
Author

abdu997 commented Sep 12, 2018

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
Copy link
Owner

lukeed commented Sep 12, 2018

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
		}
	}
}

@lukeed lukeed closed this as completed Sep 12, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants