Skip to content

Instantly share code, notes, and snippets.

@adeelibr
Created July 22, 2018 15:55
Show Gist options
  • Save adeelibr/d4d7cc9c1903d77437aef61a1d94ff12 to your computer and use it in GitHub Desktop.
Save adeelibr/d4d7cc9c1903d77437aef61a1d94ff12 to your computer and use it in GitHub Desktop.
Abort Controller Axios Seperated Files Example
import React, { Component } from 'react';
import axios from 'axios';
// API
import { onLoadUser } from './UserAPI';
class Example extends Component {
signal = axios.CancelToken.source();
state = {
isLoading: false,
user: {},
}
componentDidMount() {
this.onLoadUser();
}
componentWillUnmount() {
this.signal.cancel('Api is being canceled');
}
onLoadUser = async () => {
try {
this.setState({ isLoading: true });
const data = await onLoadUser(this.signal.token);
this.setState({ user: data, isLoading: true });
} catch (error) {
if (axios.isCancel(err)) {
console.log('Error: ', err.message); // => prints: Api is being canceled
} else {
this.setState({ isLoading: false });
}
}
}
render() {
return (
<div>
<pre>{JSON.stringify(this.state.user, null, 2)}</pre>
</div>
)
}
};
}
export const onLoadUser = async myCancelToken => {
try {
const { data } = await axios.get('https://randomuser.me/api/', {
cancelToken: myCancelToken,
})
return data;
} catch (error) {
throw error;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment