npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

axios-tracked

v0.1.1

Published

enhanced axios functionality

Downloads

27

Readme

Axios Tracked

An enhancement to run alongside Axios, adding named tracking, event subscriptions, and easy cancellation for API requests.

Install

$ npm install axios axios-tracked

Demo Project

Clone and run the "Axios-Tracked-Example" project to see examples of how to use the axios-tracked module and test out its capabilities. Whilst this project is React and Typescript, there is no necessity to sticking with those, as this package is designed to be low dependency.

Usage

To use axios-tracked, simply import the package and begin by creating an API instnace using the createInstance function. This API instance works much the same way as the main Axios API instance, however it provides some additional functionality to make requests and cancellations easier, as well as the ability to handle side-effects based on request events.

Basics

The recommended approach to using axios-tracked is to export and use a single api instance with which all endpoints can be defined.

const axiosTracked = require('axios-tracked');

// create instance
const apiInstance = axiosTracked.createInstance({
  baseURL: 'https://jsonplaceholder.typicode.com',
  timeout: 30000,
});

// Create a GET request handler for fetching a list of Todos
const getTodos = function () {
  apiInstance
    .tracked({
      action: 'GET_TODO_LIST',
      cancelPrevious: true,
    })
    .get('/todos')
    .then(function (res) {
      console.log(res.data);
    })
    .catch(function (err) {
      console.error(err);
    });
};

// Create a GET request handler for fetching a Todo by its Id
const getTodoById = function (id) {
  apiInstance
    .tracked({
      action: 'GET_TODO',
    })
    .get('/todos/' + id)
    .then(function (res) {
      console.log(res.data);
    })
    .catch(function (err) {
      console.error(err);
    });
};

// Create a POST request handler for a posting a new Todo
const createTodo = function (newTodo) {
  apiInstance
    .tracked({
      action: 'CREATE_TODO',
      throwError: true,
    })
    .post('/todos', newTodo)
    .then(function (res) {
      console.log(res.data);
    })
    .catch(function (err) {
      console.error(err);
    });
};

Events

Events add an additional method by which side-effects within an app can be triggered. This is based on the lifecycle of each request and how it is resolved end to end without needing to monitor each and every request individually. This is done via the subscribe method on the API instance, which will always return an unsubscribe function for clean-up (see below).

Event Types

| Event Name | Emitted When | Properties | | ----------- | ------------------------------------------------------------------ | -------------------------- | | request | the request is triggered | action, type | | success | the response has returned successfully | action, type, result | | cancelled | the request was cancelled prior to a response being returned | action, type | | error | the response has failed and threw and error | action, type, error | | resolved | any one of success, error, or cancelled events are triggered | action, type |

Event Properties

| Property | Description | | -------- | ---------------------------------------------------------------------------------------- | | action | the id / name of the tracked request | | error | an instance of AxiosError which may have some additional boolean flags: is401, is502 | | result | the Axios Response object returned as part of a successful response | | type | one of request, success, error, or cancelled. |

NOTE: resolved events will contain the type property of the triggering event type

Subscribing to Events

// Declare loading states
let isLoadingItem = false;
let isLoadingList = false;

// Handle incoming api event by action name
function handleOnRequest(req) {
  switch (req.action) {
    case 'GET_TODO':
      isLoadingItem = true;
      break;
    case 'GET_TODO_LIST':
      isLoadingList = true;
      break;
  }
}

// Subscribe to `request` events and handle with pre-defined function
apiInstance.subscribe('request', handleOnRequest);

// Subscribe to `resolved` events and handle with in-situ function
apiInstance.subscribe('resolved', function (res) {
  switch (res.action) {
    case 'GET_TODO':
      // Only stop loading IF the request succeeded
      isLoadingItem = res.type === 'success';
      break;
    case 'GET_TODO_LIST':
      isLoadingList = false;
      break;
  }
});

// Subscribe to `error` events to handle thrown errors
apiInstance.subscribe('error', function (res) {
  if (res.action == 'GET_TODO_LIST') {
    // specifically handle the action 'GET_TODOS_LIST'
    alert('Could not fetch all Todos');
  } else if (res.error && res.error.message) {
    // use the API error message in a callback
    alert(res.error.message);
  }
});

// Subscribe to `success` events to handle newly created TODOs
const unsubscribe = apiInstance.subscribe('success', function (res) {
  if (res.action != 'CREATE_TODO') {
    return;
  }

  const newTodo = res.result.data;

  if (newTodo) {
    alert('Successfully created a new TODO with id', newTodo.id);
  }
});

// In the case of clean-up, calling `unsubscribe` will remove the listeners
function onUmount() {
  unsubscribe();
}

Typescript Support

Typescript is built into axios-tracked so there is no need to install additional @type packages. The example below demonstrates how some of the earlier code could be written with Typescript.

import { createInstance, ErrorListener, TrackedEvent, TrackedInstance } from 'axios-tracked';

// create instance
const apiInstance: TrackedInstance = axiosTracked.createInstance({
  baseURL: 'https://jsonplaceholder.typicode.com',
  timeout: 30000,
});

enum TodoActions {
  CREATE = 'CREATE_TODO',
  GET = 'GET_TODO',
  LIST = 'GET_TODO_LIST',
}

// Create a GET request handler for fetching a list of Todos
const getTodos = () => apiInstance.tracked({
    action: TodoActions.LIST,
    cancelPrevious: true
  })
  .get<TodoModel[]>('/todos')
  .then((res) =>console.log(res.data))
  .catch((err) => console.error(err));

// Create a GET request handler for fetching a Todo by its Id
const getTodoById = (id: string) => apiInstance.tracked({
    action: TodoActions.GET
  })
  .get<TodoModel>(`/todos/${id}`)
  .then((res) =>console.log(res.data))
  .catch((err) => console.error(err));

// Create a POST request handler for a posting a new Todo
const createTodo = (todo: Omit<TodoModel, 'id'>) => apiInstance.tracked({
    action: TodoActions.CREATE,
    throwError: true
  })
  .post<TodoModel>(`/todos`)
  .then((res) =>console.log(res.data))
  .catch((err) => console.error(err));

// Define a typed handler to be registered with the `susbcribe` method
const handleError: ErrorListener<TodoActions> = ({ action, error }) => {
  if (action == TodoActions.LIST) {
    // specifically handle the action 'GET_TODOS_LIST'
    alert('Could not fetch all Todos')
  } else if (error?.message) {
    // use the API error message in a callback
    alert(error.message)
  }
};

// In the case of clean-up, calling `unsubscribe` will remove the listener
const unsubscribe = apiInstance.subscribe(
  TrackedEvent.ERROR,
  handleError
});

Upcoming Features

In the near future, the plan is to add a complimentary package for React to make it easier to "hook" into API events to simplify the passing of API state to Component Props.

More to come