Axios API Calls
Mock API calls
Axios API call using SWR
Address values have been initialised using useSWR with Axios fetcher like below:
src/states/menu.ts
import { useMemo } from 'react';
// third party
import useSWR, { mutate } from 'swr';
// types
import { MenuProps } from 'types/menu';
const initialState: MenuProps = {
openedItem: '',
isDashboardDrawerOpened: false
};
export const endpoints = {
key: 'api/menu',
master: 'master'
};
export function useGetMenuMaster() {
// to fetch initial state based on endpoints
const { data, isLoading } = useSWR(endpoints.key + endpoints.master, () => initialState, {
revalidateIfStale: false,
revalidateOnFocus: false,
revalidateOnReconnect: false
});
const memoizedValue = useMemo(
() => ({
menuMaster: data ?? (initialState as MenuProps),
menuMasterLoading: isLoading
}),
[data, isLoading]
);
return memoizedValue;
}
export function handlerDrawerOpen(isDashboardDrawerOpened: boolean) {
// to update `isDashboardDrawerOpened` local state based on key
mutate(
endpoints.key + endpoints.master,
(currentMenuMaster = initialState) => {
return { ...currentMenuMaster, isDashboardDrawerOpened };
},
false
);
}
export function handlerActiveItem(openedItem: string) {
// to update `openedItem` local state based on key
mutate(
endpoints.key + endpoints.master,
(currentMenuMaster = initialState) => {
return { ...currentMenuMaster, openedItem };
},
false
);
}
Set the default axios baseURL for calling the API
Open the .env file and edit VITE_APP_API_URL.
.env
## Backend API URL
VITE_APP_API_URL=
Example: With BaseUrl
// third party
import axios from 'axios';
// project imports
import { AUTH_USER_KEY } from 'config';
const axiosServices = axios.create({
baseURL: import.meta.env.VITE_APP_API_URL || (typeof window !== 'undefined' ? window.location.origin : 'http://localhost:3001')
});
// ==============================|| AXIOS MIDDLEWARE ||============================== //
axiosServices.interceptors.request.use(
async (config) => {
const storedValue = typeof window !== 'undefined' ? localStorage.getItem(AUTH_USER_KEY) : null;
const parsedValue = storedValue && JSON.parse(storedValue);
if (parsedValue?.access_token) {
config.headers['Authorization'] = `Bearer ${parsedValue.access_token}`;
}
return config;
},
(error) => {
return Promise.reject(error);
}
);
axiosServices.interceptors.response.use(
(response) => response,
(error) => {
if (error.response.status === 401 && !window.location.href.includes('/login')) {
redirectWithBasePath('/login');
}
return Promise.reject((error.response && error.response.data) || 'Wrong Services');
}
);
export default axiosServices;
export function redirectWithBasePath(path: string) {
const basePath = import.meta.env.VITE_APP_BASE_URL || ''; // adjust for Vite, CRA, etc.
window.location.pathname = `${basePath.replace(/\/$/, '')}${path}`;
}
Axios API call using SWR
Address values have been initialised using useSWR with Axios fetcher like below:
src/states/menu.js
import { useMemo } from 'react';
// third party
import useSWR, { mutate } from 'swr';
const initialState = {
openedItem: '',
isDashboardDrawerOpened: false
};
export const endpoints = {
key: 'api/menu',
master: 'master'
};
export function useGetMenuMaster() {
// to fetch initial state based on endpoints
const { data, isLoading } = useSWR(endpoints.key + endpoints.master, () => initialState, {
revalidateIfStale: false,
revalidateOnFocus: false,
revalidateOnReconnect: false
});
const memoizedValue = useMemo(
() => ({
menuMaster: data ?? initialState,
menuMasterLoading: isLoading
}),
[data, isLoading]
);
return memoizedValue;
}
export function handlerDrawerOpen(isDashboardDrawerOpened) {
// to update `isDashboardDrawerOpened` local state based on key
mutate(
endpoints.key + endpoints.master,
(currentMenuMaster = initialState) => {
return { ...currentMenuMaster, isDashboardDrawerOpened };
},
false
);
}
export function handlerActiveItem(openedItem) {
// to update `openedItem` local state based on key
mutate(
endpoints.key + endpoints.master,
(currentMenuMaster = initialState) => {
return { ...currentMenuMaster, openedItem };
},
false
);
}
Set the default axios baseURL for calling the API
Open the .env file and edit VITE_APP_API_URL.
.env
## Backend API URL
VITE_APP_API_URL=
Example: With BaseUrl
// third party
import axios from 'axios';
// project imports
import { AUTH_USER_KEY } from 'config';
const axiosServices = axios.create({
baseURL: import.meta.env.VITE_APP_API_URL || (typeof window !== 'undefined' ? window.location.origin : 'http://localhost:3001')
});
// ==============================|| AXIOS MIDDLEWARE ||============================== //
axiosServices.interceptors.request.use(
async (config) => {
const storedValue = typeof window !== 'undefined' ? localStorage.getItem(AUTH_USER_KEY) : null;
const parsedValue = storedValue && JSON.parse(storedValue);
if (parsedValue?.access_token) {
config.headers['Authorization'] = `Bearer ${parsedValue.access_token}`;
}
return config;
},
(error) => {
return Promise.reject(error);
}
);
axiosServices.interceptors.response.use(
(response) => response,
(error) => {
if (error.response.status === 401 && !window.location.href.includes('/login')) {
redirectWithBasePath('/login');
}
return Promise.reject((error.response && error.response.data) || 'Wrong Services');
}
);
export default axiosServices;
export function redirectWithBasePath(path) {
const basePath = import.meta.env.VITE_APP_BASE_URL || ''; // adjust for Vite, CRA, etc.
window.location.pathname = `${basePath.replace(/\/$/, '')}${path}`;
}
Last updated
Was this helpful?