Skip to content

Adding delay in DEV requests with axios

Slowing down requests, and making DEV env feel more natural

This will allow you to test your application in a more natural way. I had this issue where it was hard to figure out of cancel-tokens worked, spinners would disappear immediately, and overall testing felt weird.

TypeScript
sleep.ts
export function sleep(ms = 2000): Promise<void> {
  console.log('Kindly remember to remove `sleep`');
  return new Promise((resolve) => setTimeout(resolve, ms));
}
TypeScript
api-client.ts
import axios from 'axios';
 
import {sleep} from '@/f/utils/sleep';
import {originUrl} from '@/f/utils/url';
 
export const client = axios.create({
  baseURL: `${originUrl}/api`,
});
TypeScript
api-client.ts
client.interceptors.response.use(async (response) => {
  // add artificial delay for dev env
  if (process.env.NODE_ENV === 'development') {
    await sleep();
  }
  return response.data;
});