Simple react hook for data polling. Executes async function every N seconds, updates state and handles all setTimeout/clearTimeout stuff for you.
-
Simple API
-
Small size (only 324 bytes)
-
Typescript support
-
Will not make additional async function call if previous doesn't complete
Using npm
npm install --save use-api-pollingOr yarn
yarn add use-api-pollingimport React from 'react'
import useAPIPolling, { APIPollingOptions } from 'use-api-polling'
import API from './api'
type DataType = {
img: string
title: string
}
const App = () => {
const fetchFunc = async () => {
const cats = await API.getCats()
return cats
}
const options: APIPollingOptions<DataType> = {
fetchFunc,
initialState: [],
delay: 5000
}
const data = useAPIPolling(options)
return <Gallery data={data} />
}| Option name | Type | Required | Description |
|---|---|---|---|
| fetchFunc | () => Promise | Yes | Function be called every N seconds. Result of this function will be passed to hooks result |
| initialState | DataType | Yes | Initial hook result. Will be returned before first fetchFunc |
| delay | number | Yes | Interval for polling in milliseconds |
| onError | (error, setData) => void | No | Callback be called after fetchFunc promise fail. setData function is used to change hook result. If option is not provided, initialState will be written after fetchFunc fail |
| updateTrigger | any | No | This variable pass as useEffect's 2nd argument to trigger update. If option is not provided, polling will start on component mount and stop on component unmount |