Better Fetch

Timeout and Retry

Timeout and retry are two options that can be used to control the request timeout and retry behavior.

Timeout

You can set the timeout in milliseconds.

fetch.ts
const  = await ("/api/users", {
    : 10000,
});

Auto Retry

You can set the retry count and interval in milliseconds.

fetch.ts
const  = await ("/api/users", {
    : 3
});

Advanced Retry Options

Better fetch provides flexible retry mechanisms with both linear and exponential backoff strategies. You can customize the retry behavior to suit your specific needs.

Basic retry with number of attempts:

fetch.ts
const  = await ("https://jsonplaceholder.typicode.com/todos/1", {
  : 3
});

Linear retry strategy:

fetch.ts
const  = await ("https://jsonplaceholder.typicode.com/todos/1", {
  : {
    : "linear",
    : 3,
    : 1000 // 1 second delay between each attempt
  }
});

Exponential backoff strategy:

fetch.ts
const  = await ("https://jsonplaceholder.typicode.com/todos/1", {
    : {
        : 3,
        : 1000, //optional
    : "exponential",
    : 5,
    : 1000, // Start with 1 second delay
    : 10000 // Cap the delay at 10 seconds, so requests would go out after 1s then 2s, 4s, 8s, 10s
  }
});

Custom retry condition:

fetch.ts
const  = await ("https://jsonplaceholder.typicode.com/todos/1", {
  : {
    : "linear",
    : 3,
    : 1000,
    : () => {
      if( === null) return true; 
      if(. === 429) return true;
      if(. !== 200) return true;
      return .().(
         => .completed === false
      ).(
         => true 
      )
    }
  }
});

Retry with callback:

fetch.ts
const  = await ("https://jsonplaceholder.typicode.com/todos/1", {
  : 3,
  : () => {
    .(`Retrying request.`);
    }
});

On this page