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 🙏

© 2024 – Pkg Stats / Ryan Hefner

@react-cmpt/react-request-hook

v5.1.0

Published

Managed request calls made easy by React Hooks

Downloads

11

Readme

react-request-hook

A React hook plugin for Axios. Lightweight and less change.

CI npm GitHub license

Fork: https://github.com/schettino/react-request-hook

Usage

Quick Start

import { useResource } from "@react-cmpt/react-request-hook";

function Profile({ userId }) {
  const [{ data, error, isLoading }] = useResource((id) => ({ url: `/user/${id}` }), [userId]);

  if (error) return <div>failed to load</div>;
  if (isLoading) return <div>loading...</div>;
  return <div>hello {data.name}!</div>;
}
import { useRequest, useResource } from "@react-cmpt/react-request-hook";

installation

yarn add axios @react-cmpt/react-request-hook

RequestProvider

import axios from "axios";
import { RequestProvider } from "@react-cmpt/react-request-hook";

// https://github.com/axios/axios#creating-an-instance
const axiosInstance = axios.create({
  baseURL: "https://example.com/",
});

ReactDOM.render(
  // custom instance
  <RequestProvider instance={axiosInstance}>
    <App />
  </RequestProvider>,
  document.getElementById("root"),
);

RequestProvider config

| config | type | explain | | -------------------- | --------------- | ---------------------------------------------------------- | | instance | object | axios instance | | cache | object | false | Customized cache collections. Or close. (Default on) | | cacheKey | function | Global custom formatted cache keys | | cacheFilter | function | Global callback function to decide whether to cache or not | | customCreateReqError | function | Custom format error data |

useRequest

| option | type | explain | | ------------------- | -------- | ------------------------------------------------ | | fn | function | get AxiosRequestConfig function | | options.onCompleted | function | This function is passed the query's result data. | | options.onError | function | This function is passed an RequestError object |

// js
const [createRequest, { hasPending, cancel }] = useRequest((id) => ({
  url: `/user/${id}`,
  method: "DELETE",
}));

// tsx
const [createRequest, { hasPending, cancel }] = useRequest((id: string) =>
  // response.data: Result. AxiosResponse<Result>
  request<Result>({
    url: `/user/${id}`,
    method: "DELETE",
  }),
);
interface CreateRequest {
  // Promise function
  ready: () => Promise<[Payload<TRequest>, AxiosRestResponse]>;
  // Axios Canceler. clear current request.
  cancel: Canceler;
}

type HasPending = boolean;
// Axios Canceler. clear all pending requests(CancelTokenSource).
type Cancel = Canceler;
useEffect(() => {
  const { ready, cancel } = createRequest(id);

  ready()
    .then((res) => {
      console.log(res);
    })
    .catch((err) => {
      console.log(err);
    });
  return cancel;
}, [id]);
// options: onCompleted, onError
const [createRequest, { hasPending, cancel }] = useRequest(
  (id) => ({
    url: `/user/${id}`,
    method: "DELETE",
  }),
  {
    onCompleted: (data, other) => console.info(data, other),
    onError: (err) => console.info(err),
  },
);

useResource

| option | type | explain | | -------------------- | --------------------------- | ------------------------------------------------------------------- | | fn | function | get AxiosRequestConfig function | | parameters | array | fn function parameters. effect dependency list | | options.cache | object | false | Customized cache collections. Or close | | options.cacheKey | string| number | function | Custom cache key value | | options.cacheFilter | function | Callback function to decide whether to cache or not | | options.filter | function | Request filter. if return a falsy value, will not start the request | | options.defaultState | object | Initialize the state value. {data, other, error, isLoading} | | options.onCompleted | function | This function is passed the query's result data. | | options.onError | function | This function is passed an RequestError object |

// js
const [{ data, error, isLoading }, fetch] = useResource((id) => ({
  url: `/user/${id}`,
  method: "GET",
}));

// tsx
const [reqState, fetch] = useResource((id: string) =>
  // response.data: Result. AxiosResponse<Result>
  request<Result>({
    url: `/user/${id}`,
    method: "GET",
  }),
);
interface ReqState {
  // Result
  data?: Payload<TRequest>;
  // other axios response. Omit<AxiosResponse, "data">
  other?: AxiosRestResponse;
  // normalized error
  error?: RequestError<Payload<TRequest>>;
  isLoading: boolean;
  cancel: Canceler;
}

type Fetch = (...args: Parameters<TRequest>) => Canceler;

The request can also be triggered passing its arguments as dependencies to the useResource hook.

const [userId, setUserId] = useState();

const [reqState] = useResource(
  (id) => ({
    url: `/user/${id}`,
    method: "GET",
  }),
  [userId],
);

// no parameters
const [reqState] = useResource(
  () => ({
    url: "/users/",
    method: "GET",
  }),
  [],
);

// conditional
const [reqState, request] = useResource(
  (id) => ({
    url: `/user/${id}`,
    method: "GET",
  }),
  [userId],
  {
    filter: (id) => id !== "12345",
  },
);

request("12345"); // custom request is still useful

// options: onCompleted, onError
const [reqState] = useResource(
  () => ({
    url: "/users/",
    method: "GET",
  }),
  [],
  {
    onCompleted: (data, other) => console.info(data, other),
    onError: (err) => console.info(err),
  },
);

cache

https://codesandbox.io/s/react-request-hook-cache-9o2hz

other

request

The request function allows you to define the response type coming from it. It also helps with creating a good pattern on defining your API calls and the expected results. It's just an identity function that accepts the request config and returns it. Both useRequest and useResource extract the expected and annotated type definition and resolve it on the response.data field.

const api = {
  getUsers: () => {
    return request<Users>({
      url: "/users",
      method: "GET",
    });
  },

  getUserPosts: (userId: string) => {
    return request<UserInfo>({
      url: `/users/${userId}`,
      method: "GET",
    });
  },
};

createRequestError

The createRequestError normalizes the error response. This function is used internally as well. The isCancel flag is returned, so you don't have to call axios.isCancel later on the promise catch block.

interface RequestError<T> {
  data?: T;
  message: string;
  code?: string | number;
  isCancel: boolean;
  original: AxiosError<T>;
}

License

MIT