Skip to content

Commit d09cd62

Browse files
grgmoFacebook Github Bot 9
authored andcommitted
Add support for ontimeout and onerror handler when using XMLHttpRequest for Android and iOS
Summary:Currently React-Native does not have `ontimeout` and `onerror` handlers for [XMLHttpRequest](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest). This is an extension to [No timeout on XMLHttpRequest](facebook#4648). With addition to two handlers, both Android and iOS can now handle `ontimeout` if request times out and `onerror` when there is general network error. **Test plan** Code has been tested on both Android and iOS with [Charles](https://www.charlesproxy.com/) by setting a breakpoint on the request which fires `ontimeout` when the request waits beyond `timeout` time and `onerror` when there is network error. **Usage** JavaScript - ``` var request = new XMLHttpRequest(); function onLoad() { console.log(request.status); }; function onTimeout() { console.log('Timeout'); }; function onError() { console.log('General network error'); }; request.onload = onLoad; request.ontimeout = onTimeout; request.onerr Closes facebook#6841 Differential Revision: D3178859 Pulled By: lexs fb-gh-sync-id: 30674570653e92ab5f7e74bd925dd5640fc862b6 fbshipit-source-id: 30674570653e92ab5f7e74bd925dd5640fc862b6
1 parent 967dbd0 commit d09cd62

File tree

8 files changed

+248
-20
lines changed

8 files changed

+248
-20
lines changed

Examples/UIExplorer/XHRExample.android.js

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ var {
2929
var XHRExampleHeaders = require('./XHRExampleHeaders');
3030
var XHRExampleCookies = require('./XHRExampleCookies');
3131
var XHRExampleFetch = require('./XHRExampleFetch');
32-
32+
var XHRExampleOnTimeOut = require('./XHRExampleOnTimeOut');
3333

3434
// TODO t7093728 This is a simplified XHRExample.ios.js.
3535
// Once we have Camera roll, Toast, Intent (for opening URLs)
@@ -297,6 +297,11 @@ exports.examples = [{
297297
render() {
298298
return <XHRExampleCookies/>;
299299
}
300+
}, {
301+
title: 'Time Out Test',
302+
render() {
303+
return <XHRExampleOnTimeOut/>;
304+
}
300305
}];
301306

302307
var styles = StyleSheet.create({

Examples/UIExplorer/XHRExample.ios.js

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ var {
3232

3333
var XHRExampleHeaders = require('./XHRExampleHeaders');
3434
var XHRExampleFetch = require('./XHRExampleFetch');
35+
var XHRExampleOnTimeOut = require('./XHRExampleOnTimeOut');
3536

3637
class Downloader extends React.Component {
3738
state: any;
@@ -331,6 +332,11 @@ exports.examples = [{
331332
render() {
332333
return <XHRExampleHeaders/>;
333334
}
335+
}, {
336+
title: 'Time Out Test',
337+
render() {
338+
return <XHRExampleOnTimeOut/>;
339+
}
334340
}];
335341

336342
var styles = StyleSheet.create({
Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,110 @@
1+
/**
2+
* The examples provided by Facebook are for non-commercial testing and
3+
* evaluation purposes only.
4+
*
5+
* Facebook reserves all rights not expressly granted.
6+
*
7+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
8+
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
9+
* FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL
10+
* FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
11+
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
12+
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
13+
*
14+
* @flow
15+
*/
16+
'use strict';
17+
18+
var React = require('react');
19+
var ReactNative = require('react-native');
20+
var {
21+
StyleSheet,
22+
Text,
23+
TouchableHighlight,
24+
View,
25+
} = ReactNative;
26+
27+
class XHRExampleOnTimeOut extends React.Component {
28+
state: any;
29+
xhr: XMLHttpRequest;
30+
31+
constructor(props: any) {
32+
super(props);
33+
this.state = {
34+
status: '',
35+
loading: false
36+
};
37+
}
38+
39+
loadTimeOutRequest() {
40+
this.xhr && this.xhr.abort();
41+
42+
var xhr = this.xhr || new XMLHttpRequest();
43+
44+
xhr.onerror = ()=> {
45+
console.log('Status ', xhr.status);
46+
console.log('Error ', xhr.responseText);
47+
};
48+
49+
xhr.ontimeout = () => {
50+
this.setState({
51+
status: xhr.responseText,
52+
loading: false
53+
});
54+
};
55+
56+
xhr.onload = () => {
57+
console.log('Status ', xhr.status);
58+
console.log('Response ', xhr.responseText);
59+
};
60+
61+
xhr.open('GET', 'https://httpbin.org/delay/5'); // request to take 5 seconds to load
62+
xhr.timeout = 2000; // request times out in 2 seconds
63+
xhr.send();
64+
this.xhr = xhr;
65+
66+
this.setState({loading: true});
67+
}
68+
69+
componentWillUnmount() {
70+
this.xhr && this.xhr.abort();
71+
}
72+
73+
render() {
74+
var button = this.state.loading ? (
75+
<View style={styles.wrapper}>
76+
<View style={styles.button}>
77+
<Text>Loading...</Text>
78+
</View>
79+
</View>
80+
) : (
81+
<TouchableHighlight
82+
style={styles.wrapper}
83+
onPress={this.loadTimeOutRequest.bind(this)}>
84+
<View style={styles.button}>
85+
<Text>Make Time Out Request</Text>
86+
</View>
87+
</TouchableHighlight>
88+
);
89+
90+
return (
91+
<View>
92+
{button}
93+
<Text>{this.state.status}</Text>
94+
</View>
95+
);
96+
}
97+
}
98+
99+
var styles = StyleSheet.create({
100+
wrapper: {
101+
borderRadius: 5,
102+
marginBottom: 5,
103+
},
104+
button: {
105+
backgroundColor: '#eeeeee',
106+
padding: 8,
107+
},
108+
});
109+
110+
module.exports = XHRExampleOnTimeOut;

Libraries/Network/RCTNetworking.m

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -385,6 +385,7 @@ - (void)sendRequest:(NSURLRequest *)request
385385
}
386386
NSArray *responseJSON = @[task.requestID,
387387
RCTNullIfNil(error.localizedDescription),
388+
error.code == kCFURLErrorTimedOut ? @YES : @NO
388389
];
389390

390391
[_bridge.eventDispatcher sendDeviceEventWithName:@"didCompleteNetworkResponse"

Libraries/Network/XMLHttpRequestBase.js

Lines changed: 25 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,8 @@ class XMLHttpRequestBase {
6161
status: number;
6262
timeout: number;
6363
responseURL: ?string;
64+
ontimeout: ?Function;
65+
onerror: ?Function;
6466

6567
upload: ?{
6668
onprogress?: (event: Object) => void;
@@ -79,6 +81,7 @@ class XMLHttpRequestBase {
7981
_responseType: ResponseType;
8082
_sent: boolean;
8183
_url: ?string;
84+
_timedOut: boolean;
8285

8386
constructor() {
8487
this.UNSENT = UNSENT;
@@ -91,11 +94,15 @@ class XMLHttpRequestBase {
9194
this.onload = null;
9295
this.upload = undefined; /* Upload not supported yet */
9396
this.timeout = 0;
97+
this.ontimeout = null;
98+
this.onerror = null;
9499

95100
this._reset();
96101
this._method = null;
97102
this._url = null;
98103
this._aborted = false;
104+
this._timedOut = false;
105+
this._hasError = false;
99106
}
100107

101108
_reset(): void {
@@ -115,6 +122,7 @@ class XMLHttpRequestBase {
115122
this._lowerCaseResponseHeaders = {};
116123

117124
this._clearSubscriptions();
125+
this._timedOut = false;
118126
}
119127

120128
// $FlowIssue #10784535
@@ -249,11 +257,14 @@ class XMLHttpRequestBase {
249257
}
250258
}
251259

252-
_didCompleteResponse(requestId: number, error: string): void {
260+
_didCompleteResponse(requestId: number, error: string, timeOutError: boolean): void {
253261
if (requestId === this._requestId) {
254262
if (error) {
255263
this.responseText = error;
256264
this._hasError = true;
265+
if (timeOutError) {
266+
this._timedOut = true;
267+
}
257268
}
258269
this._clearSubscriptions();
259270
this._requestId = null;
@@ -362,17 +373,25 @@ class XMLHttpRequestBase {
362373
onreadystatechange.call(this, null);
363374
}
364375
if (newState === this.DONE && !this._aborted) {
365-
this._sendLoad();
376+
if (this._hasError) {
377+
if (this._timedOut) {
378+
this._sendEvent(this.ontimeout);
379+
} else {
380+
this._sendEvent(this.onerror);
381+
}
382+
}
383+
else {
384+
this._sendEvent(this.onload);
385+
}
366386
}
367387
}
368388

369-
_sendLoad(): void {
389+
_sendEvent(newEvent: ?Function): void {
370390
// TODO: workaround flow bug with nullable function checks
371-
var onload = this.onload;
372-
if (onload) {
391+
if (newEvent) {
373392
// We should send an event to handler, but since we don't process that
374393
// event anywhere, let's leave it empty
375-
onload(null);
394+
newEvent(null);
376395
}
377396
}
378397
}
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
'use strict';
2+
3+
jest
4+
.autoMockOff()
5+
.dontMock('XMLHttpRequestBase');
6+
7+
const XMLHttpRequestBase = require('XMLHttpRequestBase');
8+
9+
describe('XMLHttpRequestBase', function(){
10+
var xhr;
11+
12+
beforeEach(() => {
13+
xhr = new XMLHttpRequestBase();
14+
xhr.ontimeout = jest.fn();
15+
xhr.onerror = jest.fn();
16+
xhr.onload = jest.fn();
17+
xhr.didCreateRequest(1);
18+
});
19+
20+
afterEach(() => {
21+
xhr = null;
22+
});
23+
24+
it('should call ontimeout function when the request times out', function(){
25+
xhr._didCompleteResponse(1, 'Timeout', true);
26+
27+
expect(xhr.ontimeout).toBeCalledWith(null);
28+
expect(xhr.onerror).not.toBeCalled();
29+
expect(xhr.onload).not.toBeCalled();
30+
});
31+
32+
it('should call onerror function when the request times out', function(){
33+
xhr._didCompleteResponse(1, 'Generic error');
34+
35+
expect(xhr.onerror).toBeCalledWith(null);
36+
expect(xhr.ontimeout).not.toBeCalled();
37+
expect(xhr.onload).not.toBeCalled();
38+
});
39+
40+
it('should call onload function when there is no error', function(){
41+
xhr._didCompleteResponse(1, null);
42+
43+
expect(xhr.onload).toBeCalledWith(null);
44+
expect(xhr.onerror).not.toBeCalled();
45+
expect(xhr.ontimeout).not.toBeCalled();
46+
});
47+
48+
});

0 commit comments

Comments
 (0)