Giter Club home page Giter Club logo

react-waiter's Introduction

React Waiter

NPM Build Status license: MIT

Installation

npm i react-waiter --save

See it in action https://billyxs.github.io/react-waiter/

Basic Usage

import React from 'react';
import { useWaiter } from 'react-waiter';

function requestCreator() {
  return Promise.resolve({ name: 'react-waiter' })
}

function Component() {
  const { 
    response, 
    isPending, 
    isResolved 
  } = useWaiter(requestCreator);

  if (isPending) {
    return <span>working...</span>;
  }

  if (response) {
    return <span>{response.name} success!</span>;
  }
}

useWaiter(requestCreator, requestParams)

useWaiter() is a react hook for handling your async requests. Provide a function(requestCreator) for react-waiter to call and you're set.

function requestCreator() {
  return getItems()
}

const waiter = useWaiter(requestCreator)

If you need to provide dynamic parameters to your request, this can be handled with the requestParams, the second useWaiter() argument.

Say we have an API to request an item by ID, called getItemById().

function requestCreator({ id }) {
  return getItemById(id)
}

const { callWaiter} = useWaiter(requestCreator, { id: 1 })

// When you are done with item 1, get item 2 using callWaiter()
callWaiter({ id: 2 })

<button onClick={() => {
  callWaiter({ id: 2})
}}>
  Get next item
</button>

default values

// The request ID of the waiter. This will increment with each call.
id: null,

// The params sent to the requestCreator based on the last request
params: undefined,

// the promise returned from the requestCreator
request: null,

// resolved data
response: null,

// rejected error
error: null,

// true when the request is pending
isPending: false,

// true when the request has resolved successfully
isResolved: false,

// true when the request has rejected/errored out
isRejected: false,

// true when the request has rejected or resolved
isCompleted: false,

// true if the request completed previously and is being called again
isRefreshing: false,

// true if the request is canceled from calling cancelWaiter  
isCanceled: false,

// unix timestamp in milliseconds when the request is initialzed
startTime: null,

// unix timestamp in milliseconds when the request is completes
endTime: null,

// duration in milliseconds for the request to complete 
elapsedTime: null,

// unix timestamp in milliseconds of the last update to any property
lastModified: null,

Hook properties

const {
  callWaiter,
  cancelWaiter,
  clearWaiter,

  // waiter data
  id,
  request,
  params, 
  response,
  error,

  // lifecyle
  isPending,
  isResolved,
  isRejected,
  isCompleted,
  isRefreshing,
  isCanceled,

  // timestamps
  startTime,
  endTime,
  elapsedTime,
  lastModified,
} = useWaiter(requestCreator);

callWaiter(params)

This will invoke your requestCreator with any new params. If your request previously succeeded before calling callWaiter(), calling it a second time will set isRefreshing to be true.

const { callWaiter } = useWaiter(() => myRequest()) 

callWaiter({ param: 'Hello' })

cancelWaiter()

If your request is currently pending, you may cancel the current request with cancelWaiter(). This simply ignores the request when it resolves or rejects.

If the request is interrupted, isCanceled will be true.

If the request completed, cancelWaiter() will have no effect.

const { cancelWaiter, isCanceled } = useWaiter(() => myRequest()) 

cancelWaiter()

clearWaiter()

This will clear all hook properties to look as if the requestCreator had never been invoked. The requestCreator will stay intact and may be called again by callWaiter().

If a request is currently running, the request will not complete and any result will be ignored.

const { clearWaiter } = useWaiter(() => myRequest()) 

clearWaiter()

Waiter

Render props implementaion of the waiter.

import { Waiter } from 'react-waiter'

<Waiter
  requestCreator={(params) => Promise.resolve(params)}
  render={({
    response,
    error,
    isPending,
    isResolved,
    isRejected,
  }) => (
    <div>
      {isPending && 'Waiting...'}
      {isResolved && response}
      {isRejected && error.message}
    </div>
  )}

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.