Coder Social home page Coder Social logo

use-api-polling's Introduction

useAPIPolling

styled with prettier 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 324 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 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

use-api-polling's People

Contributors

lazyd3v avatar mrexox avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

Forkers

mrexox liahnee

use-api-polling's Issues

Hook doesn't clean up after redirect.

Hello!
I've encountered an issue with this hook. I need to conditionally redirect to another route depending on result of polling. It doesn't stop polling after redirect is done.
Here is example of code:

`
const history = useHistory();

const checkPaymentStatus = () => {
return callApi("GET", "/payStatus");
};

const pollingOptions = {
fetchFunc: checkPaymentStatus,
initialState: 1,
delay: 1000,
};

const status = useAPIPolling(pollingOptions);

if (status === 4) {
history.push("/");
}

if (status === 2) {
history.push("/thankyou");
}
`

Any ideas why it happens and how to fix it? btw thank you for this package, it would be great time-saver if not this issue.

Is It working?

Tested it in my project, it sends only first two requests and then shows no activity
Here my code:

export async function getNotifications() {
  console.log('getNotifications');
  if (!axios.defaults.headers.common['Authorization']) {
    const cookies = getCookies();
    axios.defaults.headers.common['Authorization'] = `Bearer ${cookies.access_token}`;
  }
  return axios.get(`/api/uaa/notifications/me`);
}

import React, { useState } from 'react';
import NotificationBlock from '@/components/NotificationBlock';
import { getNotifications } from '@/services/notification.service';
import useAPIPolling from 'use-api-polling';

import bell from '../../assets/images/icons/bell.svg';

import s from './BellIcon.scss';

const BellIcon = () => {
  const [isNotifShown, setNotifShown] = useState(false);

  const options = {
    fetchFunc: getNotifications,
    initialState: [],
    delay: 10000,
  }

  const resp = useAPIPolling(options);
  const notifs = resp.data || [];
  console.log('BellIcon', notifs);

  return (
    <div className={s.wrapper}>
      <img style={{ cursor: 'pointer' }} src={bell} alt="" onClick={() => setNotifShown(!isNotifShown)} />
      {notifs.length > 0 ? <div className={s.value}>{notifs.length}</div> : null}
      <NotificationBlock 
        visible={notifs.length > 0 && isNotifShown}
        notifs={notifs}
      />
    </div>
  );
};

export default BellIcon;

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.