Skip to content

Instantly share code, notes, and snippets.

@gaonkar-adi
Last active November 11, 2020 15:40
Show Gist options
  • Save gaonkar-adi/45676319bb6b1dfff5c1d7a9f025686b to your computer and use it in GitHub Desktop.
Save gaonkar-adi/45676319bb6b1dfff5c1d7a9f025686b to your computer and use it in GitHub Desktop.
React Axios Wrapper with Error Notifications
import axios from 'axios';
import { toast } from 'react-toastify';
import ConstantsList from './constants';
class API {
constructor() {
let service = axios.create({});
service.interceptors.response.use(this.handleSuccessResponse, this.handleErrorResponse);
this.service = service;
}
handleSuccessResponse(response) {
return response;
}
handleErrorResponse = (error) => {
if(error && error.response) {
switch (error.response.status) {
case 401:
toast.error(ConstantsList.ACTION_UNAUTHORIZED, { className: "error-toast" });
break;
case 404:
toast.error(ConstantsList.ACTION_NOT_FOUND, { className: "warn-toast" });
break;
case 408:
toast.error(ConstantsList.ACTION_REQUEST_TIMED_OUT, { className: "warn-toast" });
break;
case 500:
toast.error(ConstantsList.ACTION_INTERNAL_SERVER, { className: "warn-toast" });
break;
case 502:
toast.error(ConstantsList.ACTION_BAD_GATEWAY, { className: "warn-toast" });
break;
case 503:
toast.error(ConstantsList.ACTION_SERVICE_UNAVAILABLE, { className: "warn-toast" });
break;
case 507:
toast.error(ConstantsList.ACTION_INSUFFICIENT_STORAGE, { className: "warn-toast" });
break;
case 400:
toast.error(error.response.data.message, { className: "error-toast" });
break;
default:
toast.error(error.response.status + ": " + error.response.statusText, { className: "error-toast" });
break;
}
}
return Promise.reject(error)
}
get(path, callback) {
return this.service.get(path).then(
(response) => callback(response.data)
);
}
patch(path, payload, callback) {
return this.service.request({
method: 'PATCH',
url: path,
responseType: 'json',
data: payload
}).then((response) => callback(response.data));
}
post(path, payload, callback) {
return this.service.request({
method: 'POST',
url: path,
responseType: 'json',
data: payload
}).then((response) => callback(response.data));
}
}
export default new API;
@gaonkar-adi
Copy link
Author

gaonkar-adi commented Nov 11, 2020

To enable Toast Notifications, ToastContainer needs to used in index.js of the react application.
Example:
`
import { ToastContainer } from "react-toastify";
import 'react-toastify/dist/ReactToastify.css';

ReactDOM.render(
<React.StrictMode>


</React.StrictMode>,
document.getElementById('root')
);
`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment