Retries
Handling temporary network issues or server errors gracefully is crucial for a robust application. Hyper-fetch provides a powerful retries mechanism that automatically re-sends a request if it fails. This guide will walk you through configuring and using retries to improve the reliability of your data-fetching logic.
- How to enable and configure retries for a request.
- How to set a custom delay between retry attempts.
- The difference between setting retries on creation vs. dynamically.
- How to observe retry attempts in real-time.
Basic Configuration
You can configure retries directly on a request using the retry and retryTime options.
retry: The number of times to re-attempt the request after it fails.retryTime: The delay in milliseconds between each retry attempt.
Let's create a request that will fail (by pointing to a non-existent endpoint) and see how retries work.
// We are using non-existent endpoint to showcase the retry mechanism
const getUsers = client.createRequest()({
method: "GET",
endpoint: "/users-fake-endpoint",
retry: 3,
retryTime: 1000, // 1 second
});
const sendRequest = async () => {
const { data, error } = await getUsers.send();
console.log({ data, error });
};
sendRequest();
In the example above, if the request to /users-fake-endpoint fails, Hyper-fetch will automatically retry it up to 3
times, with a 1-second delay between each attempt. If all retries fail, the request will finally return an error.
Dynamic Configuration
You can also configure retries dynamically using the .setRetry() and .setRetryTime() methods. This is useful when
you need to change the retry behavior based on application state or other conditions.
These methods return a new Request instance, leaving the original request unchanged.
Here, we created a new request getUsersWithRetries with 2 retries and a 2-second delay, without modifying the original
getUsers request.
Conditional Retries
By default, Hyper-fetch retries on any error. You can use setRetryOnError to add a condition - for example, only retry
on server errors (5xx) but not on client errors (4xx) where retrying won't help:
const getUsers = client.createRequest()({
endpoint: "/users",
retry: 3,
retryTime: 1000,
});
const smartRetry = getUsers.setRetryOnError((response) => {
// Only retry on server errors, not client errors
return response.status >= 500;
});
The callback receives the error response and must return true to allow the retry or false to stop retrying. This is
useful for avoiding unnecessary retries when the server returns a definitive error like 400 Bad Request or
404 Not Found.
You've learned how to make your requests more resilient with Hyper-fetch's retry feature!
- You can set retry attempts and delay when creating a request.
- You can dynamically adjust retry behavior using the
.setRetry()and.setRetryTime()methods. - You know that retry settings can be changed without modifying the original request.
- You can now handle temporary network failures gracefully.
