-
-
Notifications
You must be signed in to change notification settings - Fork 61
/
EventSource.react.js
82 lines (66 loc) · 1.97 KB
/
EventSource.react.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import React from "react";
import PropTypes from "prop-types";
/** An interface to server sent events in Dash */
export default class DashEventSource extends React.Component {
componentDidMount() {
const { url, withCredentials, setProps } = this.props;
this.eventSource = new EventSource(url, { withCredentials });
this.eventSource.onopen = () => {
setProps({ readyState: EventSource.OPEN });
};
this.eventSource.onmessage = (event) => {
setProps({ message: event.data });
};
this.eventSource.onerror = (event) => {
setProps({ error: JSON.stringify(event) });
};
}
componentDidUpdate() {
const { close } = this.props;
if (close) {
this.eventSource.close();
this.props.setProps({ readyState: EventSource.CLOSED });
}
}
componentWillUnmount() {
this.eventSource.close();
}
render() {
return null;
}
}
DashEventSource.propTypes = {
/**
* The ID used to identify this component in Dash callbacks.
*/
id: PropTypes.string,
/**
* Close event source
*/
close: PropTypes.bool,
/**
* Error
*/
error: PropTypes.string,
/**
* Received message
*/
message: PropTypes.string,
/**
* A number representing the state of the connection. Possible values are CONNECTING (0), OPEN (1), or CLOSED (2).
*/
readyState: PropTypes.number,
/**
* Dash-assigned callback that should be called to report property changes
* to Dash, to make them available for callbacks.
*/
setProps: PropTypes.func,
/**
* A boolean value indicating whether the EventSource object was instantiated with cross-origin (CORS) credentials set (true), or not (false, the default).
*/
withCredentials: PropTypes.bool,
/**
* A DOMString representing the URL of the source.
*/
url: PropTypes.string.isRequired,
};