Giter Site home page Giter Site logo

react-polling's Introduction

๐Ÿ”” react-polling

All Contributors

Build Status

Easy to use polling service built with react that follows the render props pattern.

Note: Read more about render props here Render Props Pattern

๐Ÿšš Installation

yarn add react-polling

or

npm i react-polling --save

โšก๏ธ Usage

Default usage (the lib will internally use fetch to make api calls)

import React from 'react';

<ReactPolling
  url={'url to poll'}
  interval= {3000} // in milliseconds(ms)
  retryCount={3} // this is optional
  onSuccess={() => console.log('handle success')}
  onFailure={() => console.log('handle failure')} // this is optional
  method={'GET'}
  headers={headers object} // this is optional
  body={JSON.stringify(data)} // data to send in a post call. Should be stringified always
  render={({ startPolling, stopPolling, isPolling }) => {
    if(isPolling) {
      return (
        <div> Hello I am polling</div>
      );
    } else {
      return (
        <div> Hello I stopped polling</div>
      );
    }
  }}
/>

Custom lib for making api calls (provide us your promise function and we will use that to make api calls)

import React from 'react';
// import of some lib for making http calls
// let's say you are using axios
import axios from "axios";

const fetchData = () => {
  // return a promise
  return axios.get("some polling url");
}

const App = () => {
  return (
    <ReactPolling
      url={'url to poll'}
      interval= {3000} // in milliseconds(ms)
      retryCount={3} // this is optional
      onSuccess={() => console.log('handle success')}
      onFailure={() => console.log('handle failure')} // this is optional
      promise={fetchData} // custom api calling function that should return a promise
      render={({ startPolling, stopPolling, isPolling }) => {
        if(isPolling) {
          return (
            <div> Hello I am polling</div>
          );
        } else {
          return (
            <div> Hello I stopped polling</div>
          );
        }
      }}
    />
  );
}

๐Ÿ“’ Api

๐Ÿ”” react-polling

Props Type Default Description
url string null url/api to poll
interval number 3000 Interval of polling
retryCount number 0 Number of times to retry when an api polling call fails
onSuccess function - Callback function on successful polling. This should return true to continue polling
onFailure function () => {} Callback function on failed polling or api failure
method string GET HTTP Method of the api to call
headers object - Any specific http headers that need to be sent with the request
body object - The data that need to be sent in a post/put call
render function - Render function to render the ui
promise function - custom function that should return a promise
backOffFactor number 1 exponential back off factor for api polling(interval*backOffFactor)
children function - React children function based on child props pattern

onSuccess (required)

This function will be called every time the polling service gets a successful response. You should return true to continue polling and false to stop polling. It has the following signature:

function onSuccess(response) {
  // You can do anything with this response, may be add to an array of some state of your react component
  // return true to continue polling
  // return false to stop polling
}

onFailure (not compulsory field)

This function will be called every time the polling service gets a failure response from the api, it can be 401 or 500 or any failure status code. You can do some cleaning up of your variables or reseting the state here.

function onFailure(error) {
  // You can log this error to some logging service
  // clean up some state and variables.
}

promise (when you need your own api calling logic and not the default fetch which this lib uses)

This function will be called every time the polling service wants to poll for some data. Ideally inside this function you should write your api calling logic.

function fetchPosts() {
  return axios.get("some url");
}

backOffFactor(default is 1) (not compulsory field)

This option is only needed if you want to exponentially increase the rate at which we poll the api. For example

  • if backOffFactor is 2 and interval is 3000, then the first polling call will be made after 3000ms
  • Next polling call will happen after interval*backOffFactor = 3000*2 = 6000ms later

๐Ÿ“ฆ Size

๐Ÿ‘ป Examples

๐Ÿ‘ Contribute

Show your โค๏ธ and support by giving a โญ. Any suggestions and pull request are welcome !

๐Ÿ“ License

MIT ยฉ viveknayyar

๐Ÿ‘ท TODO

  • Complete README
  • Add Examples and Demo
  • Test Suite

Contributors

Thanks goes to these wonderful people (emoji key):


Vivek Nayyar

๐Ÿ“– ๐Ÿ’ป ๐ŸŽจ ๐Ÿ’ก

This project follows the all-contributors specification. Contributions of any kind welcome!

react-polling's People

Contributors

dependabot[bot] avatar vivek12345 avatar

Stargazers

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

Watchers

 avatar  avatar  avatar

react-polling's Issues

Allow it to provide a context to access the poller to force poll

I think you can use React context and provide some sort of API that would be used like

const { forcePoll, isPolling }  = useReactPolling("url");

// generally use the nicer method to check if it is already polling to wait for the poll to finish this could be the default
forcePoll({ method: "nice"} );
// Other methods
// forcePoll({ method: "force"} ); don't care, just re-execute the polling routine even if it is already running
// forcePoll({ method: "queue"} ); queue it up to poll after the current poll is done, calling multiple times will queue it up some more
// forcePoll({ method: "queue_once"} ); queue it up to poll after the current poll is done, calling multiple times will still only retain one

Multiple react-polling components

Hi,

When I try to call the react-polling component multiple times from within my react app then polling works for only the first time. If I pass in different props based on change in some state, then the polling doesn't work.

Is it expected behaviour?

How is startPolling and stopPolling supposed to work?

First of all: great work!

But I don't understand how those two functions are supposed to work. Calling them in the render property like so

render={({ startPolling, stopPolling, isPolling }) => { if (this.state.view === 'results') { stopPolling(); } }}

leads to an TypeError:

TypeError: Cannot read property '_ismounted' of undefined

What I'd like to to is to stop polling for a certain state in the application and re-start it after another event occurs.

Polling empty responses?

return resp.json().then(data => {

I'm attempting to use the component for an asynchronous REST service, where the /status endpoint will respond with 202 and an empty response body until the service eventually succeeds.

However, since the response function evaluates Body.json(), I'm suspecting the polling stops on an unhandled error. Perhaps the function should guard with a test for non-empty body before evaluating Body.json()?

Support for dynamic URL

Thanks for the handy component @vivek12345 ๐Ÿ‘
I was wondering if there is anyway to modify the url on each poll - say /resource/1, /resource/2 etc. From what I could gather, this is not possible as of now?

Feature Request: Add support for providing a promise directly

Instead of having to provide the url, headers, body, etc and then that be used in fetch, it would be great if given the user the option to simply provide a promise also which is called instead.

The use case arises when you build your own clients for your backend server and want to use those, since they already incoporate your custom setup of authentication, logging, error handling etc. And you might want to use your own http client or rest client. An infact might want to use your own websocket client. Making the api generic to handle any promise leads to a lot of possibilities.

Losing all the functionality by only giving the option to use fetch therefore is not ideal.

So I would propose this api change, and if it makes sense to you then I'd be happy to make a PR.

// Adding a new prop called promise which you can provide instead of url, headers, body, etc

const customPromise = backend.service('/database/users').get(userId)

<ReactPolling 
  promise={customPromise}
  interval= {3000} // in milliseconds(ms)
  retryCount={3} // this is optional
  onSuccess={() => console.log('handle success')}
  onFailure={() => console.log('handle failure')} // this is optional
  render={({ startPolling, stopPolling, isPolling }) => {
    if(isPolling) {
      return (
        <div> Hello I am polling</div>
          <Spinner />
        </div>
      );
    } else {
      return (
        <div> Hello I stopped polling</div>
        </div>
      );
    }
  }}
/>
// Inside the libary a one line change is made like so

runPolling() {
    const { url, interval, onSuccess, onFailure, api } = this.config;

    const _this = this;
    this.poll = setTimeout(() => {
      /* onSuccess would be handled by the user of service which would either return true or false
      * true - This means we need to continue polling
      * false - This means we need to stop polling
      */
      
      const promise = this.props.promise ? this.props.promise : () => fetch(url, api)

      promise()
        .then(resp => {
          return resp.json().then(data => {
            if (resp.ok) {
              return data;
            } else {
              return Promise.reject({ status: resp.status, data });
            }
          });
        })
        .then(onSuccess)
        .then(continuePolling => {
          _this.state.isPolling && continuePolling ? _this.runPolling() : _this.stopPolling();
        })
        .catch(error => {
          if (_this.config.shouldRetry && _this.config.retryCount > 0) {
            onFailure && onFailure(error);
            _this.config.retryCount--;
            _this.runPolling();
          } else {
            onFailure && onFailure(error);
            _this.stopPolling();
          }
        });
    }, interval);
  }

Thanks for all your work on this ๐ŸŽ‰

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.