npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

use-async-request

v1.2.10

Published

A Custom React Hook for request data.

Readme

📦 use-async-request

A custom React Hook for async request.

async_300x300

Statements Branches Functions Lines

Size npm version

🎨 Features

  • 🌟 Make async request w/ loading state, and the request is cancellable
  • 🌈 Support multi resquest (request sequentially by default)
  • 🎁 Ship React UI component <AsyncRequest />
  • 💪 Type safety
  • ☘️ Size ≈ 1.2KB

🔗 Installation

npm install --save use-async-request

OR

yarn add use-async-request

🔗 CDN

If you are working w/ UNPKG

https://unpkg.com/[email protected]/lib/umd/use-async-request.min.js

🔗 Usage

👉 useAsyncRequest()

import { useAsyncRequest } from 'use-async-request'

async function getStoryById(params: Record<string, any>) {
  return axios({
    url: `item/${params.storyId}.json?print=pretty`,
    method: 'get',
    params,
    errorTitle: 'Get Hacker News new stories failed',
    signal: params.controller?.signal
  })
}

const Story: React.FC<{ storyId: number }> = ({ storyId }) => {
  const { data, loading, error, refetch, request, reset } = useAsyncRequest<any>({
    defaultData: null,
    requestFunctions: [{
      func: getStoryById,
      payload: {
        storyId
      },  
    }],
  })

  return (
    <div>
      {loading && <p>Loading...</p>}
      {error && <p>{error.message}</p>}
      {(data && data[0] && (
        <>
          <p><a href={data[0].url}>{data[0].title}</a></p>
          <p>{data[0].by}</p>
        </>
      )) || <div></div>}
      <div>
        <Button onClick={() => refetch()}>Refetch</Button>
        <Button onClick={() => reset()}>Reset</Button>
      </div>
    </div>
  )
}

👉 <AsyncRequest />

<AsyncRequest
  requestFunctions={[
    {
      func: getStoryById,
      payload: { storyId }
    }
  ]}
  success={StorySuccess}
  loading={
    <span>Loading...</span>
  }
  error={({ error, refetch }) => (
    <div>
      {error.message}
      <button onClick={() => refetch()}>refetch</button>
    </div>
  )}
/>

async function getStoryById(params) {
  return axios({
    url: `https://hacker-news.firebaseio.com/v0/item/${params.storyId}.json?print=pretty`,
    method: 'get',
    params,
    errorTitle: 'Get Hacker News story failed',
    signal: params.controller?.signal,
  });
}

const StorySuccess = ({ data, refetch }) => {
  const { title = "", url = "", by = "" } = data?.[0];
  return (
    <section>
      <p><a href={url}>{title}</a></p>
      <p>{by}</p>
      <button onClick={() => refetch()}>refetch</button>
    </section>
  );
};

Options

  • defaultData

The default data to render.

Type: any
Default: null

  • requestFunctions

The request APIs goes here. you can set payload and transform function for every single request.

Type: RequestFunction<TData>[]
Default: []

  • requestFunctions.func

The request function

Type: (...args: any[]) => Promise<any>

  • requestFunctions.payload

The request function should be like below. params can take instance of AbortController in order to cancel request.

async function getStoryIds(params) {
  return axios({
    url: `${params.storyType}.json?print=pretty`,
    method: 'get',
    params,
    errorTitle: 'Get Hacker News new stories failed',
    signal: params.controller?.signal
  })
}

Type: (...args: any[]) => Promise<any>

  • requestFunctions.transform

you can use this option to process the data that receive from Api

Type: (res: any) => TData

  • auto

using this option to make request run automatically

Type: boolean
Default: true

  • persistent

Enable data persistent. If set it true, the data that request from api will store into localStorage with given key(persistentKey), and then the next request data will be load from localStorage instead. The persistent data will always be available until persistentExpiration date.
⚠️ NOTE: refetch() and request() will ignore persistent, it will always load data through api function, AND refresh the expiration date.

Type: boolean
Default: false

  • persistentKey

The prefix key of the persisted data, which the entire key base on it. The entire key will generate like below:
⚠️ NOTE: This option needs to be set with persistent at the same time.

// generate key
const key = `${persistentKey}-${JSON.stringify(
  requestFunctions.map((req) => {
    return { name: req.func.name, payload: req.payload }
  })
)}`

Type: string
Default: ''

  • persistentExpiration

The expiration time. (ms)

Type: number
Default: 1000 * 60

Returns

  • data

The data that you request

  • loading

The loading statement

Type: boolean

  • error

  • refetch

retrigger the request action

Type: () => void

  • request

If you want to request data manually, use this.

Type: () => Promise<(Data | null)[] | null>

  • reset

Back to the start, render using the defaultData

Type: () => void

🔗 Roadmap

  • [x] Batch async request
  • [x] <AsyncRequest /> React UI components w/ demo
  • [ ] Add sequentially option for multi requests
  • [x] persistent
  • [ ] More detail docs