Skip to content

ariesjia/use-promise-call

Repository files navigation

use-promise-call

a React hook for state around promise

Actions Status NPM minified license codecov

Install

// use yarn
yarn add use-promise-call
// use npm
npm install use-promise-call

API

usePromiseCall

  • usePromiseCall(asyncMethod, parameters, options?) => { data, error, loading, reload }: usePromiseCall hooks to manage async status inside

    • asyncMethod: The method to run async

    • parameters: The initial parameters to asyncMethod, or function to get initial parameters

    • options: config

      • manual: boolean flag to manual trigger async method

        default: false

      • initial:initial data value

        default: null

      default : { interval = 100 }

result

  • data: promise resolve value
  • error: promise reject value
  • loading: status of async method
  • reload(parameters?): method of re-run async method
  • run(parameters?): method of manual trigger async method

Demo

Base

const productId = '1'
const {data: product } = usePromiseCall(loadProduct, productId)
return product && <div>{product.name}</div>

Parallel

const productId = '1'
const {data: product } = usePromiseCall(loadProduct, productId)
const {data: comments } = usePromiseCall(loadProductComments, productId)
return product && <div>{product.name}</div>

Dependent

const productId = '1'
const {data: product, loading: productLoading} = usePromiseCall(loadProduct, productId)
const {data: store, loading: storeLoading} = usePromiseCall(loadStore, () => product.store.id)
return product && <div>{product.name}</div>