Skip to content

Instantly share code, notes, and snippets.

@minheq
Last active January 23, 2016 06:32
Show Gist options
  • Save minheq/5cde3e72a1b9f60762fe to your computer and use it in GitHub Desktop.
Save minheq/5cde3e72a1b9f60762fe to your computer and use it in GitHub Desktop.
aborting HTTP request in redux
export default class Component extends React.Component {
componentDidMount(){
this.requests = [];
this.requests.push(this.props.dispatch(fetchItem(startDate, endDate)));
}
componentWillUnmount() {
this.requests.forEach(request => request.abort());
}
}
export function fetchItem(startDate, endDate) {
return (dispatch) => {
dispatch({type: FETCH_METRICS_REQUEST});
const APIPath = `/your/path/to/API`;
const params = {startDate, endDate};
const xhr = XHR.get(APIPath, params);
trackXHR(xhr,
(response) => {dispatch(fetchItemSuccess(response));},
(error) => {dispatch(fetchItemFailure(error));});
return {abort: () => xhr.abort()};
};
}
export default (xhr, success, error) => {
xhr.onreadystatechange = () => {
if (xhr.readyState === 4 && 200 <= xhr.status && xhr.status <= 300) {
success(JSON.parse(xhr.responseText));
} else {
if (xhr.status >= 400 && xhr.readyState === 4) {
error(xhr.responseText);
}
}
};
};
export default {
get(APIPath, params) {
let paramsStr = '';
if (params) {
paramsStr += '?';
Object.keys(params).map((parameter) => {
paramsStr += parameter + '=' + params[parameter] + '&';
});
paramsStr = paramsStr.substring(0, paramsStr.lastIndexOf('&'));
}
const xhr = new XMLHttpRequest();
xhr.open('GET', APIPath + paramsStr, true);
xhr.send();
return xhr;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment