-
Notifications
You must be signed in to change notification settings - Fork 0
/
axiosConfig.js
44 lines (38 loc) · 1.36 KB
/
axiosConfig.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import axios from "axios";
import { setIsAuth } from "./redux/auth";
import { refreshToken } from "./services/api/TokenService";
import { store } from "./redux/store";
import * as SecureStore from "expo-secure-store";
const api = axios.create({
baseURL: "https://hungryhub-5ojr.onrender.com", // Set your base URL here
headers: {
"Content-Type": "application/json",
},
});
// Interceptor to handle token refresh
api.interceptors.response.use(
(response) => response,
async (error) => {
const originalRequest = error.config;
if (error.response.status === 401 && !originalRequest._retry) {
originalRequest._retry = true;
try {
//refresh the token
const newAccessToken = await refreshToken();
// Update the authorization header with the new token
await SecureStore.setItemAsync("accessToken", newAccessToken);
api.defaults.headers.common["Authorization"] =
"Bearer " + newAccessToken;
originalRequest.headers["Authorization"] = "Bearer " + newAccessToken;
// Retry the original request with the new token
return api(originalRequest);
} catch (error) {
store.dispatch(setIsAuth(false));
store.dispatch({ type: "USER_LOGOUT" });
alert("Session expired, Please login again");
}
}
return Promise.reject(error);
}
);
export default api;