na-react-network-manager
v1.0.5
Published
A powerful network request manager for React applications with built-in request queuing, caching, and retry mechanisms.
Readme
NA React Network Manager
A powerful network request manager for React applications with built-in request queuing, caching, and retry mechanisms.
Installation
npm install na-react-network-manager
# or
yarn add na-react-network-manager
## useNetwork React Hook
The `useNetwork` hook simplifies making network requests within your React applications. It handles the complexities of fetching data, managing loading states, and handling errors, allowing you to focus on your application's core logic.
### Function Signature
```typescript
function useNetwork<T = any>(config: RequestConfig): { data: T | null; loading: boolean; error: Error | null }
Parametersconfig: RequestConfigAn object that defines the configuration for the network
request.interface RequestConfig {
url: string; // The URL to make the request to. Required.
method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH'; // The HTTP method to use. Required.
headers?: Record<string, string>; // Optional headers to include in the request.
body?: any; // Optional data to send in the request body (for methods like POST, PUT, etc.).
cache?: 'default' | 'no-store' | 'reload' | 'no-cache' | 'force-cache' | 'only-if-cached'; // Optional caching behavior.
cacheTime?: number; // Optional time (in milliseconds) to cache the response.
retry?: number; // Optional number of times to retry the request if it fails.
retryDelay?: number; // Optional delay (in milliseconds) between retries.
timeout?: number; // Optional timeout (in milliseconds) for the request.
}
Return Value
An object containing the following properties:data: T | null: The data returned from the network request. Will be null if the request is still loading or an error occurred. The type T is generic, and you should specify the expected data type when calling useNetwork.loading: boolean: A boolean indicating whether the request is currently in progress. true if loading, false otherwise.error: Error | null: An Error object if the request failed, or null if the request was successful or is still loading.
Usage
Import the hook:
import { useNetwork } from 'na-react-network-manager';
Use the hook in your functional component:import React from 'react';
interface UserData {
id: number;
name: string;
email: string;
}
const MyComponent = () => {
const { data, loading, error } = useNetwork<UserData>({
url: 'https://jsonplaceholder.typicode.com/users/1',
method: 'GET',
});
if (loading) {
return <div>Loading...</div>;
}
if (error) {
return <div>Error: {error.message}</div>;
}
if (data) {
return (
<div>
<h1>{data.name}</h1>
<p>Email: {data.email}</p>
</div>
);
}
return null; // Or some default/placeholder content
};
export default MyComponent;