Last active
January 23, 2016 06:32
-
-
Save minheq/5cde3e72a1b9f60762fe to your computer and use it in GitHub Desktop.
aborting HTTP request in redux
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()}; | |
}; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} | |
}; | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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