Lesson 06-Axios Instantiation and Modularization

In large projects, modularizing and instantiating Axios offers numerous benefits, including improved code maintainability, readability, and performance optimization. By creating Axios instances, you can configure separate settings for different API endpoints or environments, while modularization helps organize code structure, making it cleaner and easier to manage.

Axios Instantiation

Axios allows you to create multiple instances, each with its own default configuration. This is particularly useful for handling requests to different APIs or in different environments.

Creating an Axios Instance:

import axios from 'axios';

const instance = axios.create({
  baseURL: 'https://api.example.com',
  timeout: 10000,
  headers: {'X-Custom-Header': 'foobar'}
});

In this example, we create an Axios instance named instance that sends all requests to https://api.example.com, with a timeout and custom headers.

Modularizing Axios

Modularizing Axios involves encapsulating Axios instances and related request functions within separate modules. This approach allows you to define specific configurations and request logic per module, keeping code clear and separated.

// api/user.js
import axios from 'axios';

const instance = axios.create({
  baseURL: 'https://api.example.com/users',
  timeout: 5000
});

export const getUser = id => instance.get(`/${id}`);

export const updateUser = (id, data) => instance.put(`/${id}`, data);

In this example, we create a user.js module containing an Axios instance and two request functions: getUser and updateUser. Both functions share the same Axios instance, inheriting its default configuration.

  • Step 1: Create an Axios Instance
    Start by importing the Axios module and using axios.create() to instantiate it. Pass a configuration object with settings like baseURL, timeout, or headers.
  • Step 2: Define Request Functions
    Within the module, define request functions for specific API calls. These functions should accept necessary parameters, such as an ID or request body data, and use the Axios instance to send requests.
  • Step 3: Export Request Functions
    Export the request functions so other modules can import and use them.
  • Step 4: Use in Other Modules
    In components or services requiring requests, import the relevant functions and call them as regular functions.

Example Code:

// app.js
import { getUser, updateUser } from './api/user';

getUser(1)
  .then(user => {
    console.log(user);
  })
  .catch(error => {
    console.error(error);
  });

updateUser(1, { name: 'John Doe' })
  .then(updatedUser => {
    console.log(updatedUser);
  })
  .catch(error => {
    console.error(error);
  });
Share your love