Skip to content

Instantly share code, notes, and snippets.

@harconst
Created May 31, 2018 09:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save harconst/494e69f0a3cc69dfeb66ec7c6392b349 to your computer and use it in GitHub Desktop.
Save harconst/494e69f0a3cc69dfeb66ec7c6392b349 to your computer and use it in GitHub Desktop.
Component connection and state management
componentDidMount() {
const subscribe = {
type: "subscribe",
channels: [
{
name: "ticker",
product_ids: ["BTC-USD"]
}
]
};
this.ws = new WebSocket("wss://ws-feed.gdax.com");
this.ws.onopen = () => {
this.ws.send(JSON.stringify(subscribe));
};
this.ws.onmessage = e => {
const value = JSON.parse(e.data);
if (value.type !== "ticker") {
return;
}
const oldBtcDataSet = this.state.lineChartData.datasets[0];
const newBtcDataSet = { ...oldBtcDataSet };
newBtcDataSet.data.push(value.price);
const newChartData = {
...this.state.lineChartData,
datasets: [newBtcDataSet],
labels: this.state.lineChartData.labels.concat(
new Date().toLocaleTimeString()
)
};
this.setState({ lineChartData: newChartData });
};
}
componentWillUnmount() {
this.ws.close();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment