Skip to content

Instantly share code, notes, and snippets.

@harconst
Created May 31, 2018 08:47
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/c5715e3bfbf5ca5dc24551ed844dc753 to your computer and use it in GitHub Desktop.
Save harconst/c5715e3bfbf5ca5dc24551ed844dc753 to your computer and use it in GitHub Desktop.
import React from "react";
import { render } from "react-dom";
import { withStyles } from "@material-ui/core/styles";
import Chart from "./chart";
const styles = theme => ({
"chart-container": {
height: 400
}
});
class App extends React.Component {
state = {
lineChartData: {
labels: [],
datasets: [
{
type: "line",
label: "BTC-USD",
backgroundColor: "rgba(0, 0, 0, 0)",
borderColor: this.props.theme.palette.primary.main,
pointBackgroundColor: this.props.theme.palette.secondary.main,
pointBorderColor: this.props.theme.palette.secondary.main,
borderWidth: "2",
lineTension: 0.45,
data: []
}
]
},
lineChartOptions: {
responsive: true,
maintainAspectRatio: false,
tooltips: {
enabled: true
},
scales: {
xAxes: [
{
ticks: {
autoSkip: true,
maxTicksLimit: 10
}
}
]
}
}
};
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();
}
render() {
const { classes } = this.props;
return (
<div className={classes["chart-container"]}>
<Chart
data={this.state.lineChartData}
options={this.state.lineChartOptions}
/>
</div>
);
}
}
export default withStyles(styles, { withTheme: true })(App);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment