Skip to content

Instantly share code, notes, and snippets.

@sakilahmmad71
Last active July 25, 2021 20:27
Show Gist options
  • Select an option

  • Save sakilahmmad71/ffed6f612aca6f212004ca8439b5a42a to your computer and use it in GitHub Desktop.

Select an option

Save sakilahmmad71/ffed6f612aca6f212004ca8439b5a42a to your computer and use it in GitHub Desktop.
Axios instance
import axios from "axios";
export default (history = null) => {
const baseURL = process.env.REACT_APP_BACKEND_URL;
let headers = {};
if (localStorage.token) {
headers.Authorization = `Bearer ${localStorage.token}`;
}
const axiosInstance = axios.create({
baseURL: baseURL,
headers,
});
axiosInstance.interceptors.response.use(
(response) =>
new Promise((resolve, reject) => {
resolve(response);
}),
(error) => {
if (!error.response) {
return new Promise((resolve, reject) => {
reject(error);
});
}
if (error.response.status === 403) {
localStorage.removeItem("token");
if (history) {
history.push("/auth/login");
} else {
window.location = "/auth/login";
}
} else {
return new Promise((resolve, reject) => {
reject(error);
});
}
}
);
return axiosInstance;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment