Mantis MUI React
v3.5.0
v3.5.0
  • Documentation
  • Pre-requisites
  • Quick Start
  • Package
  • Folder Structure
  • State Management
  • Internationalization
  • Authentication
    • Switch to Auth0
    • Switch to Firebase
    • Switch to AWS Cognito
    • Switch to Supabase
  • Axios API Calls
  • Routing
  • Project Configuration
  • Color Presets
  • Theme/Style Configuration
  • How to
    • Login as First Page
    • Dashboard as First Page
    • Render Menu from the backend
    • Remove menu render from Backend
    • Remove Authentication
      • Vite
      • NextJS
  • Figma
  • Integration
    • Seed
    • To Existing Project
    • Comparison
  • Components
    • Avatar
    • BreadCrumb
    • Button
    • Dot
    • Main Card
    • Progress
    • SnackBar
    • Tooltip
    • Transitions
  • Dependencies
  • Roadmap
  • Support
  • Changelog
  • Mantis Eco System
  • FAQ
Powered by GitBook
On this page

Axios API Calls

Mock API calls

Axios API call using SWR

  1. Address values have been initialized using useSWR with Axios fetcher like below:

src/api/address.ts
import useSWR, { mutate } from 'swr';
import { useMemo } from 'react';

// utils
import { fetcher } from 'utils/axios';

// types
import { Address } from 'types/e-commerce';

const endpoints = {
  key: 'api/address',
  list: '/list', // server URL
  insert: '/new', // server URL
  update: '/edit', // server URL
  delete: '/delete' // server URL
};

export function useGetAddress() {
  const { data, isLoading, error, isValidating } = useSWR(endpoints.key + endpoints.list, fetcher, {
    revalidateIfStale: false,
    revalidateOnFocus: false,
    revalidateOnReconnect: false
  });

  const memoizedValue = useMemo(
    () => ({
      address: data?.address as Address[],
      addressLoading: isLoading,
      addressError: error,
      addressValidating: isValidating,
      addressEmpty: !isLoading && !data?.address?.length
    }),
    [data, error, isLoading, isValidating]
  );

  return memoizedValue;
}

...
  1. You can mutate the product list with Axios call, like below,

src/api/products.ts
export async function productFilter(filter) {
  const newProducts = await axios.post(endpoints.key + endpoints.filter, { filter });

  // to update local state based on key
  mutate(
    endpoints.key + endpoints.list,
    (currentProducts) => {
      return {
        ...currentProducts,
        products: newProducts.data
      };
    },
    false
  );
}

Set default axios baseURL for call API

Open the .env file and edit VITE_APP_API_URL.

.env
## Backend API URL
VITE_APP_API_URL=

You can configure the same for next.js as well.

Axios has been configured in the folder src\utils\axios.js

Example 1: With BaseUrl

import axios, { AxiosRequestConfig } from 'axios';

const axiosServices = axios.create({ baseURL: import.meta.env.VITE_APP_API_URL || 'http://localhost:3010/' });

// ==============================|| AXIOS - FOR MOCK SERVICES ||============================== //

axiosServices.interceptors.request.use(
  async (config) => {
    const accessToken = localStorage.getItem('serviceToken');
    if (accessToken) {
      config.headers['Authorization'] = `Bearer ${accessToken}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

axiosServices.interceptors.response.use(
  (response) => response,
  (error) => {
    if (error.response.status === 401 && !window.location.href.includes('/login')) {
      window.location.pathname = '/maintenance/500';
    }
    return Promise.reject((error.response && error.response.data) || 'Wrong Services');
  }
);

export default axiosServices;

export const fetcher = async (args: string | [string, AxiosRequestConfig]) => {
  const [url, config] = Array.isArray(args) ? args : [args];

  const res = await axiosServices.get(url, { ...config });

  return res.data;
};

export const fetcherPost = async (args: string | [string, AxiosRequestConfig]) => {
  const [url, config] = Array.isArray(args) ? args : [args];

  const res = await axiosServices.post(url, { ...config });

  return res.data;
};

Example 2: Without BaseUrl

You can set the entire URL in Axios request. Do not use common Axios instances src\utils\axios.jsinstead use directly Axios library.

import { useCallback, useState } from 'react';

// third-party
import axios from 'axios';

// project-imports
import { UserProfile } from 'types/users';

// ==============================|| AXIOS - USER ||============================== //

function UserList() {
  const [users, setUsers] = useState([]);

  const getUsers = useCallback(async () => {
    try {
      const response = await axios.get('https://www.domain-xyz.com/api/users');
      setUsers(response.data.users);
    } catch (error) {
      console.log(error);
    }
  }, []);

  useEffect(() => {
    getUsers();
  }, [getUsers]);

  return (
    <div>
      {users.map((user: UserProfile[], index: number) => (
        <div key={index}>{user.name}</div>
      ))}
    </div>
  );
}

Axios API call using SWR

  1. Address values have been initialized using useSWR with Axios fetcher like below:

src/api/address.js
import useSWR, { mutate } from 'swr';
import { useMemo } from 'react';

// utils
import { fetcher } from 'utils/axios';

// types
import { Address } from 'types/e-commerce';

const endpoints = {
  key: 'api/address',
  list: '/list', // server URL
  insert: '/new', // server URL
  update: '/edit', // server URL
  delete: '/delete' // server URL
};

export function useGetAddress() {
  const { data, isLoading, error, isValidating } = useSWR(endpoints.key + endpoints.list, fetcher, {
    revalidateIfStale: false,
    revalidateOnFocus: false,
    revalidateOnReconnect: false
  });

  const memoizedValue = useMemo(
    () => ({
      address: data?.address as Address[],
      addressLoading: isLoading,
      addressError: error,
      addressValidating: isValidating,
      addressEmpty: !isLoading && !data?.address?.length
    }),
    [data, error, isLoading, isValidating]
  );

  return memoizedValue;
}

...
  1. You can mutate the product list with Axios call, like below,

src/api/products.js
export async function productFilter(filter) {
  const newProducts = await axios.post(endpoints.key + endpoints.filter, { filter });

  // to update local state based on key
  mutate(
    endpoints.key + endpoints.list,
    (currentProducts) => {
      return {
        ...currentProducts,
        products: newProducts.data
      };
    },
    false
  );
}

Set default axios baseURL for call API

Open the .env file and edit VITE_APP_API_URL.

.env
## Backend API URL
VITE_APP_API_URL=

You can configure the same for next.js as well.

Axios has been configured in the folder src\utils\axios.js

Example 1: With BaseUrl

import axios from 'axios';

const axiosServices = axios.create({ baseURL: import.meta.env.VITE_APP_API_URL || 'http://localhost:3010/' });

// ==============================|| AXIOS - FOR MOCK SERVICES ||============================== //

axiosServices.interceptors.request.use(
  async (config) => {
    const accessToken = localStorage.getItem('serviceToken');
    if (accessToken) {
      config.headers['Authorization'] = `Bearer ${accessToken}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

axiosServices.interceptors.response.use(
  (response) => response,
  (error) => {
    if (error.response.status === 401 && !window.location.href.includes('/login')) {
      window.location.pathname = '/maintenance/500';
    }
    return Promise.reject((error.response && error.response.data) || 'Wrong Services');
  }
);

export default axiosServices;

export const fetcher = async (args) => {
  const [url, config] = Array.isArray(args) ? args : [args];

  const res = await axiosServices.get(url, { ...config });

  return res.data;
};

export const fetcherPost = async (args) => {
  const [url, config] = Array.isArray(args) ? args : [args];

  const res = await axiosServices.post(url, { ...config });

  return res.data;
};

Example 2: Without BaseUrl

You can set the entire URL in Axios request. Do not use common Axios instances src\utils\axios.jsinstead use directly Axios library.

import { useCallback, useState } from 'react';

// third-party
import axios from 'axios';

// project-imports
import { UserProfile } from 'types/users';

// ==============================|| AXIOS - USER ||============================== //

function UserList() {
  const [users, setUsers] = useState([]);

  const getUsers = useCallback(async () => {
    try {
      const response = await axios.get('https://www.domain-xyz.com/api/users');
      setUsers(response.data.users);
    } catch (error) {
      console.log(error);
    }
  }, []);

  useEffect(() => {
    getUsers();
  }, [getUsers]);

  return (
    <div>
      {users.map((user: UserProfile[], index: number) => (
        <div key={index}>{user.name}</div>
      ))}
    </div>
  );
}

Axios API call using SWR

  1. Address values have been initialized using useSWR with Axios fetcher like below:

src/api/address.ts
import useSWR, { mutate } from 'swr';
import { useMemo } from 'react';

// utils
import { fetcher } from 'utils/axios';

// types
import { Address } from 'types/e-commerce';

const endpoints = {
  key: 'api/address',
  list: '/list', // server URL
  insert: '/new', // server URL
  update: '/edit', // server URL
  delete: '/delete' // server URL
};

export function useGetAddress() {
  const { data, isLoading, error, isValidating } = useSWR(endpoints.key + endpoints.list, fetcher, {
    revalidateIfStale: false,
    revalidateOnFocus: false,
    revalidateOnReconnect: false
  });

  const memoizedValue = useMemo(
    () => ({
      address: data?.address as Address[],
      addressLoading: isLoading,
      addressError: error,
      addressValidating: isValidating,
      addressEmpty: !isLoading && !data?.address?.length
    }),
    [data, error, isLoading, isValidating]
  );

  return memoizedValue;
}

...
  1. You can mutate the product list with Axios call, like below,

src/api/products.ts
export async function productFilter(filter) {
  const newProducts = await axios.post(endpoints.key + endpoints.filter, { filter });

  // to update local state based on key
  mutate(
    endpoints.key + endpoints.list,
    (currentProducts) => {
      return {
        ...currentProducts,
        products: newProducts.data
      };
    },
    false
  );
}

Set default axios baseURL for call API

Open the .env file and edit VITE_APP_API_URL.

.env
## Backend API URL
VITE_APP_API_URL=

You can configure the same for next.js as well.

Axios has been configured in the folder src\utils\axios.js

Example 1: With BaseUrl

import axios, { AxiosRequestConfig } from 'axios';

const axiosServices = axios.create({ baseURL: import.meta.env.VITE_APP_API_URL || 'http://localhost:3010/' });

// ==============================|| AXIOS - FOR MOCK SERVICES ||============================== //

axiosServices.interceptors.request.use(
  async (config) => {
    const accessToken = localStorage.getItem('serviceToken');
    if (accessToken) {
      config.headers['Authorization'] = `Bearer ${accessToken}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

axiosServices.interceptors.response.use(
  (response) => response,
  (error) => {
    if (error.response.status === 401 && !window.location.href.includes('/login')) {
      window.location.pathname = '/maintenance/500';
    }
    return Promise.reject((error.response && error.response.data) || 'Wrong Services');
  }
);

export default axiosServices;

export const fetcher = async (args: string | [string, AxiosRequestConfig]) => {
  const [url, config] = Array.isArray(args) ? args : [args];

  const res = await axiosServices.get(url, { ...config });

  return res.data;
};

export const fetcherPost = async (args: string | [string, AxiosRequestConfig]) => {
  const [url, config] = Array.isArray(args) ? args : [args];

  const res = await axiosServices.post(url, { ...config });

  return res.data;
};

Example 2: Without BaseUrl

You can set the entire URL in Axios request. Do not use common Axios instances src\utils\axios.jsinstead use directly Axios library.

import { useCallback, useState } from 'react';

// third-party
import axios from 'axios';

// project-imports
import { UserProfile } from 'types/users';

// ==============================|| AXIOS - USER ||============================== //

function UserList() {
  const [users, setUsers] = useState([]);

  const getUsers = useCallback(async () => {
    try {
      const response = await axios.get('https://www.domain-xyz.com/api/users');
      setUsers(response.data.users);
    } catch (error) {
      console.log(error);
    }
  }, []);

  useEffect(() => {
    getUsers();
  }, [getUsers]);

  return (
    <div>
      {users.map((user: UserProfile[], index: number) => (
        <div key={index}>{user.name}</div>
      ))}
    </div>
  );
}

Axios API call using SWR

  1. Address values have been initialized using useSWR with Axios fetcher like below:

src/api/address.js
import useSWR, { mutate } from 'swr';
import { useMemo } from 'react';

// utils
import { fetcher } from 'utils/axios';

// types
import { Address } from 'types/e-commerce';

const endpoints = {
  key: 'api/address',
  list: '/list', // server URL
  insert: '/new', // server URL
  update: '/edit', // server URL
  delete: '/delete' // server URL
};

export function useGetAddress() {
  const { data, isLoading, error, isValidating } = useSWR(endpoints.key + endpoints.list, fetcher, {
    revalidateIfStale: false,
    revalidateOnFocus: false,
    revalidateOnReconnect: false
  });

  const memoizedValue = useMemo(
    () => ({
      address: data?.address as Address[],
      addressLoading: isLoading,
      addressError: error,
      addressValidating: isValidating,
      addressEmpty: !isLoading && !data?.address?.length
    }),
    [data, error, isLoading, isValidating]
  );

  return memoizedValue;
}

...
  1. You can mutate the product list with Axios call, like below,

src/api/products.js
export async function productFilter(filter) {
  const newProducts = await axios.post(endpoints.key + endpoints.filter, { filter });

  // to update local state based on key
  mutate(
    endpoints.key + endpoints.list,
    (currentProducts) => {
      return {
        ...currentProducts,
        products: newProducts.data
      };
    },
    false
  );
}

Set default axios baseURL for call API

Open the .env file and edit VITE_APP_API_URL.

.env
## Backend API URL
VITE_APP_API_URL=

You can configure the same for next.js as well.

Axios has been configured in the folder src\utils\axios.js

Example 1: With BaseUrl

import axios from 'axios';

const axiosServices = axios.create({ baseURL: import.meta.env.VITE_APP_API_URL || 'http://localhost:3010/' });

// ==============================|| AXIOS - FOR MOCK SERVICES ||============================== //

axiosServices.interceptors.request.use(
  async (config) => {
    const accessToken = localStorage.getItem('serviceToken');
    if (accessToken) {
      config.headers['Authorization'] = `Bearer ${accessToken}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

axiosServices.interceptors.response.use(
  (response) => response,
  (error) => {
    if (error.response.status === 401 && !window.location.href.includes('/login')) {
      window.location.pathname = '/maintenance/500';
    }
    return Promise.reject((error.response && error.response.data) || 'Wrong Services');
  }
);

export default axiosServices;

export const fetcher = async (args) => {
  const [url, config] = Array.isArray(args) ? args : [args];

  const res = await axiosServices.get(url, { ...config });

  return res.data;
};

export const fetcherPost = async (args) => {
  const [url, config] = Array.isArray(args) ? args : [args];

  const res = await axiosServices.post(url, { ...config });

  return res.data;
};

Example 2: Without BaseUrl

You can set the entire URL in Axios request. Do not use common Axios instances src\utils\axios.jsinstead use directly Axios library.

import { useCallback, useState } from 'react';

// third-party
import axios from 'axios';

// project-imports
import { UserProfile } from 'types/users';

// ==============================|| AXIOS - USER ||============================== //

function UserList() {
  const [users, setUsers] = useState([]);

  const getUsers = useCallback(async () => {
    try {
      const response = await axios.get('https://www.domain-xyz.com/api/users');
      setUsers(response.data.users);
    } catch (error) {
      console.log(error);
    }
  }, []);

  useEffect(() => {
    getUsers();
  }, [getUsers]);

  return (
    <div>
      {users.map((user: UserProfile[], index: number) => (
        <div key={index}>{user.name}</div>
      ))}
    </div>
  );
}
PreviousSwitch to SupabaseNextRouting