feat : add hook axios
This commit is contained in:
45
src/hooks/useAxios.ts
Normal file
45
src/hooks/useAxios.ts
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
// src/hooks/useAxios.ts
|
||||||
|
import { useNavigate } from "react-router-dom";
|
||||||
|
import axios from "axios";
|
||||||
|
import store from "../redux/store";
|
||||||
|
import { setToken } from "../redux/slices/token";
|
||||||
|
|
||||||
|
const useAxios = () => {
|
||||||
|
const navigate = useNavigate();
|
||||||
|
|
||||||
|
const instance = axios.create({
|
||||||
|
baseURL: "https://ping.soheilkhaledabadi.ir/api/v1",
|
||||||
|
maxBodyLength: Infinity,
|
||||||
|
});
|
||||||
|
|
||||||
|
instance.interceptors.request.use(
|
||||||
|
(config) => {
|
||||||
|
const state = store.getState();
|
||||||
|
const token = state.token.token;
|
||||||
|
if (token) {
|
||||||
|
config.headers.Authorization = `Bearer ${token}`;
|
||||||
|
}
|
||||||
|
return config;
|
||||||
|
},
|
||||||
|
(error) => {
|
||||||
|
return Promise.reject(error);
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
instance.interceptors.response.use(
|
||||||
|
(response) => {
|
||||||
|
return response;
|
||||||
|
},
|
||||||
|
(error) => {
|
||||||
|
if (error.response && error.response.status === 401) {
|
||||||
|
store.dispatch(setToken(''));
|
||||||
|
navigate('/login');
|
||||||
|
}
|
||||||
|
return Promise.reject(error);
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
return instance;
|
||||||
|
};
|
||||||
|
|
||||||
|
export default useAxios;
|
||||||
41
src/http.ts
Normal file
41
src/http.ts
Normal file
@@ -0,0 +1,41 @@
|
|||||||
|
import axios from "axios";
|
||||||
|
import store from "./redux/store";
|
||||||
|
import { setToken } from "./redux/slices/token";
|
||||||
|
import { useNavigate } from "react-router-dom";
|
||||||
|
|
||||||
|
|
||||||
|
const navigate = useNavigate()
|
||||||
|
|
||||||
|
const instance = axios.create({
|
||||||
|
baseURL: "https://ping.soheilkhaledabadi.ir/api/v1",
|
||||||
|
maxBodyLength: Infinity,
|
||||||
|
});
|
||||||
|
|
||||||
|
axios.interceptors.request.use(
|
||||||
|
(config) => {
|
||||||
|
const state = store.getState();
|
||||||
|
const token = state.token.token;
|
||||||
|
if (token) {
|
||||||
|
config.headers.Authorization = `Bearer ${token}`;
|
||||||
|
}
|
||||||
|
return config;
|
||||||
|
},
|
||||||
|
(error) => {
|
||||||
|
return Promise.reject(error);
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
axios.interceptors.response.use(
|
||||||
|
(response) => {
|
||||||
|
return response;
|
||||||
|
},
|
||||||
|
(error) => {
|
||||||
|
if (error.response && error.response.status === 401) {
|
||||||
|
navigate('/login')
|
||||||
|
store.dispatch(setToken(''));
|
||||||
|
}
|
||||||
|
return Promise.reject(error);
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
export default instance;
|
||||||
Reference in New Issue
Block a user