use-api-poller-worker
v1.0.2
Published
React hook for api-poller-worker
Downloads
3
Maintainers
Readme
use-api-poller-worker
React hook for api-poller-worker
use-api-poller-worker
is a React hook that you can use to integrate api-poller-worker
into your React app.
Table of contents
- Installation
- Usage
- API
- Functions
- Types
⇡ Top
Installation
npm install use-api-poller-worker
⇡ Top
Usage
This hook takes the same options as the ApiPollerWorker
class from api-poller-worker
, plus an extra callback
argument which will be called when the underlying worker emits a message.
It's recommended to wrap your callback in React.useCallback
, so that your app does not unnecessarily re-render multiple times.
const MyComponent = () => {
const [items, setItems] = React.useState<Item>(null);
const callback = React.useCallback<(data: Msg<Item>) => void>(data => {
setItems(data);
}, [setItems]);
useApiPollerWorker<Item>({
workerUrl: '<my api endpoint>',
}, callback);
return {
<div>
{items}
</div>
};
};
⇡ Top
API
Functions
useApiPollerWorker
This is the default export.
import useApiPollerWorker from 'use-api-poller-worker';
function useApiPollerWorker<T extends {}>(
options: ApiPollerWorkerOptions,
callback: (data: Msg<T>) => void,
)
Both ApiPollerWorkerOptions
and Msg<T>
come from api-poller-worker
. You might want to import Msg<T>
for type safety. This library re-exports Msg<T>
for convenience.
useApiPollerWorker
also accepts a generic, T
for the type of resource you're polling.
⇡ Top
Types
Msg<T>
Represents the contents of a message from the underlying polling library.
import { Msg } from 'use-api-poller-worker';
interface Msg<T> {
newItems: Records<T>;
updatedItems: Records<T>;
removedItems: string[];
}