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,

Set default axios baseURL for call API

Open the .env file and edit 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

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.