Axios API Calls
Mock API calls
Axios API call using SWR
Address values have been initialised using useSWR with Axios fetcher like below:
import { useMemo } from 'react';
// third-party
import useSWR, { mutate } from 'swr';
import { v4 as UIDV4 } from 'uuid';
// project-imports
import { fetcher } from 'utils/axios';
// types
import { EventInput } from '@fullcalendar/common';
export const endpoints = {
  key: 'api/calendar/events',
  add: '/add', // server URL
  update: '/update', // server URL
  delete: '/delete' // server URL
};
export function useGetEvents() {
  const { data, isLoading, error, isValidating } = useSWR(endpoints.key, fetcher, {
    revalidateIfStale: false,
    revalidateOnFocus: false,
    revalidateOnReconnect: false
  });
  const memoizedValue = useMemo(
    () => ({
      events: data?.events as EventInput[],
      eventsLoading: isLoading,
      eventsError: error,
      eventsValidating: isValidating,
      eventsEmpty: !isLoading && !data?.length
    }),
    [data, error, isLoading, isValidating]
  );
  return memoizedValue;
}
export async function createEvent(newEvent: Omit<EventInput, 'id'>) {
  // to update local state based on key
  mutate(
    endpoints.key,
    (currentEvents: any) => {
      const addedEvents: EventInput[] = [...currentEvents.events, { ...newEvent, id: UIDV4() }];
      return {
        ...currentEvents,
        events: addedEvents
      };
    },
    false
  );
  // to hit server
  // you may need to refetch latest data after server hit and based on your logic
  //   const data = { newEvent };
  //   await axios.post(endpoints.key + endpoints.add, data);
}
export async function updateEvent(
  eventId: string,
  updatedEvent: Partial<{
    allDay: boolean;
    start: Date | null;
    end: Date | null;
  }>
) {
  // to update local state based on key
  mutate(
    endpoints.key,
    (currentEvents: any) => {
      const updatedEvents: EventInput[] = currentEvents.events.map((event: EventInput) =>
        event.id === eventId ? { ...event, ...updatedEvent } : event
      );
      return {
        ...currentEvents,
        events: updatedEvents
      };
    },
    false
  );
  // to hit server
  // you may need to refetch latest data after server hit and based on your logic
  //   const data = { newEvent };
  //   await axios.post(endpoints.key + endpoints.update, data);
}
export async function deleteEvent(eventId: string) {
  // to update local state based on key
  mutate(
    endpoints.key,
    (currentEvents: any) => {
      const nonDeletedEvent = currentEvents.events.filter((event: EventInput) => event.id !== eventId);
      return {
        ...currentEvents,
        events: nonDeletedEvent
      };
    },
    false
  );
  // to hit server
  // you may need to refetch latest data after server hit and based on your logic
  //   const data = { newEvent };
  //   await axios.post(endpoints.key + endpoints.delete, data);
}
You can mutate the event create and update with an Axios call, like below,
if (selectedEvent && selectedEvent.id) {
          await updateEvent(selectedEvent.id, transformedValues);
        } else {
          await createEvent(transformedValues);
}Set the default axios baseURL to call the API
Open the src\utils\axios.ts file and edit VITE_APP_API_URL.
const VITE_APP_API_URL = 'https://mock-data-api-nextjs.vercel.app/';Axios has been configured in the folder src\utils\axios.ts
import axios, { AxiosRequestConfig } from 'axios';
const VITE_APP_API_URL = 'https://mock-data-api-nextjs.vercel.app/';
const axiosServices = axios.create({ baseURL: VITE_APP_API_URL || 'http://localhost:3010/' });
// ==============================|| AXIOS - FOR MOCK SERVICES ||============================== //
axiosServices.interceptors.request.use(
  async (config) => {
    config.headers['Authorization'] =
      'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiI1ZTg2ODA5MjgzZTI4Yjk2ZDJkMzg1MzciLCJpYXQiOjE3NDM0MDMxMjEsImV4cCI6MTc0MzQ4OTUyMX0.hvqWYTc1NOylXAp0fA0LmRF6xlfeiCniIV5vjfGteg0';
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);
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;
};
Axios API call using SWR
Address values have been initialized using useSWR with Axios fetcher like below:
import { useMemo } from 'react';
// third-party
import useSWR, { mutate } from 'swr';
import { v4 as UIDV4 } from 'uuid';
// project-imports
import { fetcher } from 'utils/axios';
export const endpoints = {
  key: 'api/calendar/events',
  add: '/add', // server URL
  update: '/update', // server URL
  delete: '/delete' // server URL
};
export function useGetEvents() {
  const { data, isLoading, error, isValidating } = useSWR(endpoints.key, fetcher, {
    revalidateIfStale: false,
    revalidateOnFocus: false,
    revalidateOnReconnect: false
  });
  const memoizedValue = useMemo(
    () => ({
      events: data?.events,
      eventsLoading: isLoading,
      eventsError: error,
      eventsValidating: isValidating,
      eventsEmpty: !isLoading && !data?.length
    }),
    [data, error, isLoading, isValidating]
  );
  return memoizedValue;
}
export async function createEvent(newEvent) {
  // to update local state based on key
  mutate(
    endpoints.key,
    (currentEvents) => {
      const addedEvents = [...currentEvents.events, { ...newEvent, id: UIDV4() }];
      return {
        ...currentEvents,
        events: addedEvents
      };
    },
    false
  );
  // to hit server
  // you may need to refetch latest data after server hit and based on your logic
  //   const data = { newEvent };
  //   await axios.post(endpoints.key + endpoints.add, data);
}
export async function updateEvent(eventId, updatedEvent) {
  // to update local state based on key
  mutate(
    endpoints.key,
    (currentEvents) => {
      const updatedEvents = currentEvents.events.map((event) => (event.id === eventId ? { ...event, ...updatedEvent } : event));
      return {
        ...currentEvents,
        events: updatedEvents
      };
    },
    false
  );
  // to hit server
  // you may need to refetch latest data after server hit and based on your logic
  //   const data = { newEvent };
  //   await axios.post(endpoints.key + endpoints.update, data);
}
export async function deleteEvent(eventId) {
  // to update local state based on key
  mutate(
    endpoints.key,
    (currentEvents) => {
      const nonDeletedEvent = currentEvents.events.filter((event) => event.id !== eventId);
      return {
        ...currentEvents,
        events: nonDeletedEvent
      };
    },
    false
  );
  // to hit server
  // you may need to refetch latest data after server hit and based on your logic
  //   const data = { newEvent };
  //   await axios.post(endpoints.key + endpoints.delete, data);
}You can mutate the event create and update with Axios call, like below,
if (selectedEvent && selectedEvent.id) {
    await updateEvent(selectedEvent.id, transformedValues);
 } else {
    await createEvent(transformedValues);
}Set the default axios baseURL for call the API
Open the src\utils\axios.js file and edit VITE_APP_API_URL.
const VITE_APP_API_URL = 'https://mock-data-api-nextjs.vercel.app/';Axios has been configured in the folder src\utils\axios.js
import axios from 'axios';
const VITE_APP_API_URL = 'https://mock-data-api-nextjs.vercel.app/';
const axiosServices = axios.create({ baseURL: VITE_APP_API_URL || 'http://localhost:3010/' });
// ==============================|| AXIOS - FOR MOCK SERVICES ||============================== //
axiosServices.interceptors.request.use(
  async (config) => {
    config.headers['Authorization'] =
      'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiI1ZTg2ODA5MjgzZTI4Yjk2ZDJkMzg1MzciLCJpYXQiOjE3NDM0MDMxMjEsImV4cCI6MTc0MzQ4OTUyMX0.hvqWYTc1NOylXAp0fA0LmRF6xlfeiCniIV5vjfGteg0';
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);
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;
};
Last updated