Created
May 31, 2018 09:02
-
-
Save harconst/494e69f0a3cc69dfeb66ec7c6392b349 to your computer and use it in GitHub Desktop.
Component connection and state management
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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