1.0.8 • Published 9 months ago

use-api-handler v1.0.8

Weekly downloads
-
License
ISC
Repository
github
Last release
9 months ago

use-api-handler

A versatile hook for handling API requests in React applications.

npm version Build Status License

Table of Contents

Installation

npm install use-api-handler

Usage

import React from 'react';
import useApiHandler from 'use-api-handler';

function App() {
  const { data, loading, error, sendRequest } = useApiHandler('https://api.example.com/data');

  return (
    <div>
      {loading && <p>Loading...</p>}
      {error && <p>Error: {error.message}</p>}
      {data && <pre>{JSON.stringify(data, null, 2)}</pre>}
      <button onClick={() => sendRequest('GET')}>Fetch Data</button>
    </div>
  );
}

export default App;

Features

Simplifies API requests in React applications Pagination support with fetchPaginatedData function Caching of API responses using fetchCachedData Error handling and automatic retries with sendRetriableRequest Custom request headers and authentication support Clean cancellation and cleanup on unmounting

Examples

Check out the examples directory for more usage examples and integration scenarios.

API Reference

useApiHandler(initialUrl, initialData, debounceDelay) Parameters initialUrl: Initial API endpoint URL. initialData (optional): Initial data for the hook. Default: null. debounceDelay (optional): Delay in milliseconds for URL debouncing. Default: 300. Returns An object with the following properties and functions:

data: The fetched data. loading: A boolean indicating if the request is in progress. error: An error object if the request encountered an error. setUrl(url): Update the API endpoint URL. sendRequest(method, requestData, requestConfig): Send a custom API request. fetchPaginatedData(page, pageSize): Fetch paginated data. fetchCachedData(): Fetch cached data or perform a new request if not cached. sendAuthenticatedRequest(method, requestData, token): Send an authenticated API request. sendRetriableRequest(method, requestData, requestConfig, retries, delay): Send a retriable API request.

Contributing

Contributions are welcome! Please read CONTRIBUTING.md for details on how to contribute to this project.

License

This project is licensed under the MIT License. See LICENSE for more information.

1.0.8

9 months ago

1.0.7

9 months ago

1.0.6

9 months ago

1.0.5

9 months ago

1.0.4

9 months ago

1.0.3

9 months ago

1.0.2

9 months ago

1.0.1

9 months ago

1.0.0

9 months ago