Axios API Calls

Mock API calls

Axios API call using SWR

Products values has been initialized using useSWR with Axios fetcher like below:

src/api/products.ts
export function useGetProducts() {
  const { data, isLoading, error, isValidating } = useSWR(endpoints.key + endpoints.list, fetcher, {
    revalidateIfStale: true,
    revalidateOnFocus: true,
    revalidateOnReconnect: true
  });

  const memoizedValue = useMemo(
    () => ({
      products: data?.products,
      productsLoading: isLoading,
      productsError: error,
      productsValidating: isValidating,
      productsEmpty: !isLoading && !data?.products?.length
    }),
    [data, error, isLoading, isValidating]
  );

  return memoizedValue;
}

You can mutate products 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 next.config.js file and edit NEXT_APP_API_URL.

next.config.js
NEXT_APP_API_URL:

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

Example 1: With baseUrl

src/utils/axios.js
import axios, { AxiosRequestConfig } from 'axios';
import { getSession } from 'next-auth/react';

const axiosServices = axios.create({ baseURL: process.env.NEXT_APP_API_URL });

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

/**
 * Request interceptor to add Authorization token to request
 */
axiosServices.interceptors.request.use(
  async (config) => {
    const session = await getSession();
    if (session?.token.accessToken) {
      config.headers['Authorization'] = `Bearer ${session?.token.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 = '/login';
    }
    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.

src\utils\axios.js
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>
  );
}

Last updated