Berry React
v4.0.0
v4.0.0
  • Introduction
  • Package
  • Getting Started
    • Pre-requisites
    • Quick Start
    • Mock backend
    • Deployment
    • Licensing
  • Setup
    • Seed
    • To Existing Project
  • Folder Structure
  • State Management
  • Multi Language
  • Authentication
    • Firebase
    • Auth0
    • AWS Cognito
    • Supabase
  • API Calls
  • Routing
    • New Menu
    • Login as First Page
    • Skip Login
    • Render Menu from the backend
    • Remove menu render via backend
  • Theme
    • Configuration
    • Presets
    • Style
      • Color
      • Typography
      • Overrides
      • Shadows
    • Layouts
    • Logo
  • How to
    • Remove eslint
    • Remove prettier
  • Components
    • Avatar
    • AnimateButton
    • Accordion
    • Breadcrumbs
    • Chip
    • ImageList
    • MainCard
    • Transitions
    • SubCard
  • Dependencies
  • Support
    • Roadmap
    • Changelog
    • FAQ
  • Berry Eco System
Powered by GitBook
On this page
  • Set default axios base URL to call API
  • With baseUrl
  • Without baseUrl

Was this helpful?

API Calls

API calls

Set default axios base URL to call API

Open .env file and edit REACT_APP_API_URL to your backend.

.env

## Backend API URL
VITE_APP_API_URL=https://mock-data-api-nextjs.vercel.app/

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

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

With baseUrl

/**
 * axios setup to use mock service
 */

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 = '/login';
        }
        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;
};

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>
  );
}

Was this helpful?