forked from tiaanduplessis/react-native-websocket
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
52 lines (43 loc) · 1.19 KB
/
index.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
/* global WebSocket */
/* eslint no-unused-vars: "off" */
import React, {Component} from 'react'
import PropTypes from 'prop-types'
class WS extends Component {
state = {
ws: null
}
static defaultProps = {
reconnect: false
}
static propTypes = {
url: PropTypes.string.isRequired,
reconnect: PropTypes.bool,
onOpen: PropTypes.func,
onMessage: PropTypes.func,
onError: PropTypes.func,
onClose: PropTypes.func
}
send = (data) => this.state.ws.send(data)
componentDidMount () {
this.reconnect = !!this.props.reconnect
this._handleWebSocketSetup()
}
componentWillUnmount () {
this.reconnect = false
this.state.ws.close()
}
render () {
return null
}
_handleWebSocketSetup = () => {
const ws = new WebSocket(this.props.url)
ws.onopen = () => {
this.props.onOpen && this.props.onOpen()
}
ws.onmessage = (event) => { this.props.onMessage && this.props.onMessage(event) }
ws.onerror = (error) => { this.props.onError && this.props.onError(error) }
ws.onclose = () => this.reconnect ? this._handleWebsocketSetup() : (this.props.onClose && this.props.onClose())
this.setState({ws})
}
}
export default WS