Skip to content

useSafeAxios

useSafeAxios

Provides a safe wrapper around Axios to handle HTTP requests with automatic error handling and request cancellation. The function returns an object with methods: safeGet, safePost, safePut, and safeDelete, each allowing for HTTP requests with a specified method, URL, payload, and optional configuration. Each request is safeguarded with a timeout and can be aborted using an AbortController. Errors, including network issues and HTTP status errors, are caught and returned in a structured format.

Returns:

  • object containing safeGet, safePost, safePut, and safeDelete methods for making HTTP requests safely.

safeRequest (async)

Nested in: useSafeAxios

A helper function to abstract the request logic away from the main useSafeAxios function. It wraps the Axios request in a try-catch block and sets up a timeout and abort controller for safety.

Parameters:

  • method: - The type of HTTP request to be made.
  • url: - The URL of the request.
  • payload: - The data to be sent with the request.
  • config: - Optional config object for Axios.

Returns:

  • promise that resolves to an object with 'data' and 'error' properties, containing the response data and error information respectively. If the request was successful, 'data' will be the response data and 'error' will be null; if the request failed, 'data' will be null and 'error' will contain the error information.

handleError

Nested in: useSafeAxios

Handles errors that occur in the safeRequest function. It logs the error and returns an object with 'data' and 'error' properties. If the request was successful, 'data' will be the response data and 'error' will be null; if the request failed, 'data' will be null and 'error' will contain the error information.

Parameters:

  • err: - The error object to be handled.

Returns:

  • object with 'data' and 'error' properties containing the response data and error information respectively.

Released under the MIT License.