@joshuarileydev/use-poll
v1.0.1
Published
A React hook for polling URLs and detecting changes in text or JSON responses
Downloads
8
Maintainers
Readme
use-poll
A React hook for polling URLs and detecting changes in text or JSON responses.
Installation
npm install use-pollUsage
Text Polling
Poll a URL and detect when the text response changes:
import { usePoll } from 'use-poll';
function MyComponent() {
const { data, error, isLoading } = usePoll({
url: 'https://api.example.com/status',
outputType: 'text',
interval: 3000, // Poll every 3 seconds
});
if (error) return <div>Error: {error.message}</div>;
if (isLoading) return <div>Loading...</div>;
return <div>Status: {data}</div>;
}JSON Polling
Poll a URL and monitor a specific property for changes, then return another property:
import { usePoll } from 'use-poll';
function MyComponent() {
const { data, error, isLoading } = usePoll({
url: 'https://api.example.com/user/123',
outputType: 'json',
monitorProperty: 'user.lastModified', // Monitor this for changes
outputProperty: 'user.profile', // Return this when changes occur
interval: 5000,
});
return (
<div>
{data && (
<pre>{JSON.stringify(data, null, 2)}</pre>
)}
</div>
);
}Conditional Polling
Control when polling is active:
import { usePoll } from 'use-poll';
function MyComponent() {
const [enabled, setEnabled] = useState(false);
const { data, error, isLoading } = usePoll({
url: 'https://api.example.com/data',
outputType: 'text',
enabled, // Only poll when true
});
return (
<div>
<button onClick={() => setEnabled(!enabled)}>
{enabled ? 'Stop' : 'Start'} Polling
</button>
<div>{data}</div>
</div>
);
}API
usePoll(options)
Options
| Option | Type | Required | Description |
|--------|------|----------|-------------|
| url | string | Yes | The URL to poll |
| outputType | 'text' | 'json' | Yes | The expected response type |
| interval | number | No | Polling interval in ms (default: 5000) |
| enabled | boolean | No | Whether polling is active (default: true) |
Additional options for JSON mode
| Option | Type | Required | Description |
|--------|------|----------|-------------|
| monitorProperty | string | Yes* | Property path to monitor for changes |
| outputProperty | string | Yes* | Property path to return when changes occur |
*Required when outputType is 'json'
Returns
| Property | Type | Description |
|----------|------|-------------|
| data | T | null | The current data value |
| error | Error | null | Any error that occurred |
| isLoading | boolean | Whether a request is in progress |
Features
- ✅ TypeScript support
- ✅ Automatic change detection
- ✅ Configurable polling intervals
- ✅ Support for nested JSON properties
- ✅ Error handling
- ✅ Loading states
- ✅ Conditional polling
- ✅ Request cancellation on unmount
License
MIT
