DEV Community

Cover image for Configure Axios interceptor in few minutes...
Muhammad Fahad
Muhammad Fahad

Posted on

Configure Axios interceptor in few minutes...

Interceptors

Axios interceptors are the methods which are used for each call request using axios. Interceptors helps to transform your request before calling api request and when it gets response from the api. It's just like working as middleware.

Configuration

You need to install npm package axios-interceptor-hook

Github Repo: (https://github.com/sheikhfahad67/axios-interceptor)

Run the command on your terminal.
npm install axios react-toastify axios-interceptor-hook

Installation

npm install axios react-toastify axios-interceptor-hook

axios and react-toastify are peer dependencies and needs to be installed explicitly

Example

import { ToastContainer } from 'react-toastify';
import { useAxiosInterceptor } from 'axios-interceptor-hook';
import { useEffect } from 'react';
import 'react-toastify/dist/ReactToastify.css';
function App() {
  const { data, isPending, apiHandler } = useAxiosInterceptor();
  const config = {
    method: 'get',
    url: '/todos',
    delay: 4000,
    successMessage: 'Todos data retrieve',
    errorMessage: 'Todos data fetch error',
  };
  const getTodosData = async () => {
    await apiHandler(config);
  };
  useEffect(() => {
    getTodosData();
  }, []);
  return (
    <div>
      <ToastContainer />
      {isPending && <p>Loading.......</p>}
      {data &&
        Object.keys(data).length > 0 &&
        data?.map((todo, index) => (
          <h6 key={index + 'testing'}>{todo.title}</h6>
        ))}
    </div>
  );
}
export default App;
Enter fullscreen mode Exit fullscreen mode

Return

Fields Type Description
data Object It return the response of api (res.data)
isPending Bool For loading purpose return true while fetching and return false after completion or failure
apiHandler Func Function to give yoy control over calling when you need just by passing config

For Bearer Token

Need to save your auth token as, interceptor will automatically get it.

localStorage.setItem('authToken', <YOUR TOKEN>);

Environment Variable for Base URL

Please add env variable into your .env or .env.local file.

REACT_APP_BASE_URL="https://jsonplaceholder.typicode.com"

Config Perimeters

Fields Type Description
method string 'get', 'post', 'put', 'delete', 'patch'
url string it will be your endpoint
delay number default 5000
data Object required on post, put, patch requests
successMessage string 'Any Message'
errorMessage string 'Any Message'

Discussion (0)