0.1.4 • Published 4 years ago

use-api-polling v0.1.4

Weekly downloads
441
License
MIT
Repository
github
Last release
4 years ago

useAPIPolling

styled with prettier Travis Coverage Status Dev Dependencies

Simple react hook for data polling. Executes async function every N seconds, updates state and handles all setTimeout/clearTimeout stuff for you.

Benefits

  • Simple API

  • Small size (only 547 bytes)

  • Typescript support

  • Will not make additional async function call if previous doesn't complete

Install

Using npm

npm install --save use-api-polling

Or yarn

yarn add use-api-polling

Usage

import 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} />
}

API

APIPollingOptions<DataType>

Option nameTypeRequiredDescription
fetchFunc() => PromiseYesFunction be called every N seconds. Result of this function will be passed to hooks result
initialStateDataTypeYesInitial hook result. Will be returned before first fetchFunc
delaynumberYesInterval for polling in milliseconds
onError(error, setData) => voidNoCallback 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
updateTriggeranyNoThis 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
0.1.4

4 years ago

0.1.3

4 years ago

0.1.2

4 years ago

0.1.1

5 years ago

0.1.0

5 years ago