mercredi 25 octobre 2017

Passing websocket streaming data to child in reactJS

constructor(){
    super();
    this.state = {
        chartData : {}
    };        

    let ws = new WebSocket('link');

    ws.onopen = function () {
        console.log('Successfully connected WebSocket!');
    };

    ws.onmessage = function (msg) {
        console.log("Message: " + msg.data);
        try {

            //Parse the message
            let obj = JSON.parse(msg.data);

        }catch(err){
            console.log('Error in onmessage: ' + err);
        }

    };
}
getChartData(){
    this.setState({chartData:[2,3,4,5,6] }) //Want to send obj from onmessage
}

componentWillMount(){
    this.getChartData();

};

render() {
    return (
     <div className="wrap"> 
       <Chart chartData={this.state.chartData} />
    )
}

This works fine if I have pasted the correct code! I get the data in Chart component such as:

 constructor(props){
    super(props);
    this.state = {
        chartData:props.chartData
    };
};

My question is, how do I send the obj from the ws.onmessage function because this function receives data every second.




Aucun commentaire:

Enregistrer un commentaire