Skip to content

Commit

Permalink
Add support for ontimeout and onerror handler when using XMLHttpReque…
Browse files Browse the repository at this point in the history
…st 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](#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 #6841

Differential Revision: D3178859

Pulled By: lexs

fb-gh-sync-id: 30674570653e92ab5f7e74bd925dd5640fc862b6
fbshipit-source-id: 30674570653e92ab5f7e74bd925dd5640fc862b6
  • Loading branch information
grgmo authored and Facebook Github Bot 9 committed Apr 15, 2016
1 parent 967dbd0 commit d09cd62
Show file tree
Hide file tree
Showing 8 changed files with 248 additions and 20 deletions.
7 changes: 6 additions & 1 deletion Examples/UIExplorer/XHRExample.android.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ var {
var XHRExampleHeaders = require('./XHRExampleHeaders');
var XHRExampleCookies = require('./XHRExampleCookies');
var XHRExampleFetch = require('./XHRExampleFetch');

var XHRExampleOnTimeOut = require('./XHRExampleOnTimeOut');

// TODO t7093728 This is a simplified XHRExample.ios.js.
// Once we have Camera roll, Toast, Intent (for opening URLs)
Expand Down Expand Up @@ -297,6 +297,11 @@ exports.examples = [{
render() {
return <XHRExampleCookies/>;
}
}, {
title: 'Time Out Test',
render() {
return <XHRExampleOnTimeOut/>;
}
}];

var styles = StyleSheet.create({
Expand Down
6 changes: 6 additions & 0 deletions Examples/UIExplorer/XHRExample.ios.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ var {

var XHRExampleHeaders = require('./XHRExampleHeaders');
var XHRExampleFetch = require('./XHRExampleFetch');
var XHRExampleOnTimeOut = require('./XHRExampleOnTimeOut');

class Downloader extends React.Component {
state: any;
Expand Down Expand Up @@ -331,6 +332,11 @@ exports.examples = [{
render() {
return <XHRExampleHeaders/>;
}
}, {
title: 'Time Out Test',
render() {
return <XHRExampleOnTimeOut/>;
}
}];

var styles = StyleSheet.create({
Expand Down
110 changes: 110 additions & 0 deletions Examples/UIExplorer/XHRExampleOnTimeOut.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
/**
* The examples provided by Facebook are for non-commercial testing and
* evaluation purposes only.
*
* Facebook reserves all rights not expressly granted.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL
* FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* @flow
*/
'use strict';

var React = require('react');
var ReactNative = require('react-native');
var {
StyleSheet,
Text,
TouchableHighlight,
View,
} = ReactNative;

class XHRExampleOnTimeOut extends React.Component {
state: any;
xhr: XMLHttpRequest;

constructor(props: any) {
super(props);
this.state = {
status: '',
loading: false
};
}

loadTimeOutRequest() {
this.xhr && this.xhr.abort();

var xhr = this.xhr || new XMLHttpRequest();

xhr.onerror = ()=> {
console.log('Status ', xhr.status);
console.log('Error ', xhr.responseText);
};

xhr.ontimeout = () => {
this.setState({
status: xhr.responseText,
loading: false
});
};

xhr.onload = () => {
console.log('Status ', xhr.status);
console.log('Response ', xhr.responseText);
};

xhr.open('GET', 'https://httpbin.org/delay/5'); // request to take 5 seconds to load
xhr.timeout = 2000; // request times out in 2 seconds
xhr.send();
this.xhr = xhr;

this.setState({loading: true});
}

componentWillUnmount() {
this.xhr && this.xhr.abort();
}

render() {
var button = this.state.loading ? (
<View style={styles.wrapper}>
<View style={styles.button}>
<Text>Loading...</Text>
</View>
</View>
) : (
<TouchableHighlight
style={styles.wrapper}
onPress={this.loadTimeOutRequest.bind(this)}>
<View style={styles.button}>
<Text>Make Time Out Request</Text>
</View>
</TouchableHighlight>
);

return (
<View>
{button}
<Text>{this.state.status}</Text>
</View>
);
}
}

var styles = StyleSheet.create({
wrapper: {
borderRadius: 5,
marginBottom: 5,
},
button: {
backgroundColor: '#eeeeee',
padding: 8,
},
});

module.exports = XHRExampleOnTimeOut;
1 change: 1 addition & 0 deletions Libraries/Network/RCTNetworking.m
Original file line number Diff line number Diff line change
Expand Up @@ -385,6 +385,7 @@ - (void)sendRequest:(NSURLRequest *)request
}
NSArray *responseJSON = @[task.requestID,
RCTNullIfNil(error.localizedDescription),
error.code == kCFURLErrorTimedOut ? @YES : @NO
];

[_bridge.eventDispatcher sendDeviceEventWithName:@"didCompleteNetworkResponse"
Expand Down
31 changes: 25 additions & 6 deletions Libraries/Network/XMLHttpRequestBase.js
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,8 @@ class XMLHttpRequestBase {
status: number;
timeout: number;
responseURL: ?string;
ontimeout: ?Function;
onerror: ?Function;

upload: ?{
onprogress?: (event: Object) => void;
Expand All @@ -79,6 +81,7 @@ class XMLHttpRequestBase {
_responseType: ResponseType;
_sent: boolean;
_url: ?string;
_timedOut: boolean;

constructor() {
this.UNSENT = UNSENT;
Expand All @@ -91,11 +94,15 @@ class XMLHttpRequestBase {
this.onload = null;
this.upload = undefined; /* Upload not supported yet */
this.timeout = 0;
this.ontimeout = null;
this.onerror = null;

this._reset();
this._method = null;
this._url = null;
this._aborted = false;
this._timedOut = false;
this._hasError = false;
}

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

this._clearSubscriptions();
this._timedOut = false;
}

// $FlowIssue #10784535
Expand Down Expand Up @@ -249,11 +257,14 @@ class XMLHttpRequestBase {
}
}

_didCompleteResponse(requestId: number, error: string): void {
_didCompleteResponse(requestId: number, error: string, timeOutError: boolean): void {
if (requestId === this._requestId) {
if (error) {
this.responseText = error;
this._hasError = true;
if (timeOutError) {
this._timedOut = true;
}
}
this._clearSubscriptions();
this._requestId = null;
Expand Down Expand Up @@ -362,17 +373,25 @@ class XMLHttpRequestBase {
onreadystatechange.call(this, null);
}
if (newState === this.DONE && !this._aborted) {
this._sendLoad();
if (this._hasError) {
if (this._timedOut) {
this._sendEvent(this.ontimeout);
} else {
this._sendEvent(this.onerror);
}
}
else {
this._sendEvent(this.onload);
}
}
}

_sendLoad(): void {
_sendEvent(newEvent: ?Function): void {
// TODO: workaround flow bug with nullable function checks
var onload = this.onload;
if (onload) {
if (newEvent) {
// We should send an event to handler, but since we don't process that
// event anywhere, let's leave it empty
onload(null);
newEvent(null);
}
}
}
Expand Down
48 changes: 48 additions & 0 deletions Libraries/Network/__tests__/XMLHttpRequestBase-test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
'use strict';

jest
.autoMockOff()
.dontMock('XMLHttpRequestBase');

const XMLHttpRequestBase = require('XMLHttpRequestBase');

describe('XMLHttpRequestBase', function(){
var xhr;

beforeEach(() => {
xhr = new XMLHttpRequestBase();
xhr.ontimeout = jest.fn();
xhr.onerror = jest.fn();
xhr.onload = jest.fn();
xhr.didCreateRequest(1);
});

afterEach(() => {
xhr = null;
});

it('should call ontimeout function when the request times out', function(){
xhr._didCompleteResponse(1, 'Timeout', true);

expect(xhr.ontimeout).toBeCalledWith(null);
expect(xhr.onerror).not.toBeCalled();
expect(xhr.onload).not.toBeCalled();
});

it('should call onerror function when the request times out', function(){
xhr._didCompleteResponse(1, 'Generic error');

expect(xhr.onerror).toBeCalledWith(null);
expect(xhr.ontimeout).not.toBeCalled();
expect(xhr.onload).not.toBeCalled();
});

it('should call onload function when there is no error', function(){
xhr._didCompleteResponse(1, null);

expect(xhr.onload).toBeCalledWith(null);
expect(xhr.onerror).not.toBeCalled();
expect(xhr.ontimeout).not.toBeCalled();
});

});
Loading

0 comments on commit d09cd62

Please sign in to comment.