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-request-hook

v2.1.1

Published

Managed request calls made easy by React Hooks

Downloads

2,856

Readme

Managed, cancelable and safely typed requests.

NPM Build Status Code Coverage Bundle Size PRs Welcome MIT License

Edit react-request-hook-examples

Table of Contents

Install

# Yarn
yarn add react-request-hook axios

# NPM
npm install --save react-request-hook axios

Quick Start

import {RequestProvider} from 'react-request-hook';
import axios from 'axios';

// More info about configuration: https://github.com/axios/axios#axioscreateconfig
const axiosInstance = axios.create({
  baseURL: 'https://example.com/',
});

ReactDOM.render(
  <RequestProvider value={axiosInstance}>
    <App />
  </RequestProvider>,
  document.getElementById('root'),
);
// User Profile component
function UserProfile(props) {
  const [profile, getProfile] = useResource(id => ({
    url: `/user/${id}`,
    method: 'GET'
  })

  useEffect(() => getProfile(props.userId), [])

  if(profile.isLoading) return <Spinner />

  return (
    <ProfileScreen
      avatar={profile.data.avatar}
      email={profile.data.email}
      name={profile.data.name} />
  )
}

Usage

useResource

The useResource hook manages the request state under the hood. Its high-level API allows one request to be made at a time. Subsequent requests cancel the previous ones, leaving the call to be made with the most recent data available. The API is intended to be similar to useState and useEffect.

It requires a function as the first argument that is just a request config factory and returns a tuple with the resource state and a function to trigger the request call, which accepts the same arguments as the factory one.

const [comments, getComments] = useResource(id => ({
  url: `/post/${id}/comments`,
  method: 'get',
}));

The request function returns a canceler that allows you to easily cancel a request on a cleaning phase of a hook.

useEffect(() => {
  if (props.isDialogOpen) {
    return getComments(props.postId);
  }
}, [props.isDialogOpen]);
interface Resource {
  isLoading: boolean;

  // same as `response.data` resolved from the axios promise
  data: Payload<Request> | null;

  // Shortcut function to cancel a pending request
  cancel: (message?: string) => void;

  // normalized error
  error: RequestError | null;
}

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

const [comments] = useResource(
  (id: string) => ({
    url: `/post/${id}/comments`,
    method: 'get',
  }),
  [props.postId],
);

It has the same behavior as useEffect. Changing those values triggers another request and cancels the previous one if it's still pending.

If you want more control over the request calls or the ability to call multiple requests from the same resource or not at the same time, you can rely on the useRequest hook.

useRequest

This hook is used internally by useResource. It's responsible for creating the request function and manage the cancel tokens that are being created on each of its calls. This hook also normalizes the error response (if any) and provides a helper that cancel all pending request.

It accepts the same function signature as useResource (a function that returns an object with the Axios request config).

const [request, createRequest] = useRequest((id: string) => ({
  url: `/post/${id}/comments`,
  method: 'get',
}));
interface CreateRequest {
  // same args used on the callback provided to the hook
  (...args): {
    // cancel the requests created on this factory
    cancel: (message?: string) => void;

    ready: () => Promise;
  };
}

interface Request {
  hasPending: boolean;

  // clear all pending requests
  clear: (message?: string) => void;
}

By using it, you're responsible for handling the promise resolution. It's still canceling pending requests when unmounting the component.

useEffect(() => {
  const {ready, cancel} = createRequest(props.postId);
  ready()
    .then(setState)
    .catch(error => {
      if (error.isCancel === false) {
        setError(error);
      }
    });
  return cancel;
}, [props.postId]);

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<Posts>({
      url: `/users/${userId}/posts`,
      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 {
  // same as `response.data`, where response is the object coming from the axios promise
  data: Payload<Request>;

  message: Error['message'];

  // code on the `data` field, `error.code` or `error.response.status`
  // in the order
  code: number | string;
}

Type safety for non typescript projects

This library is entirely written in typescript, so depending on your editor you might have all the type hints out of the box. However, we also provide a payload field to be attached to the request config object, which allows you to define and use the typings for the payload of a given request. We believe that this motivates a better and clean code as we're dealing with some of the most substantial parts of our app implementation.

const api = {
  getUsers: () => {
    return {
      url: '/users',
      method: 'GET',
      payload: [{
        id: String(),
        age: Number(),
        likesVideoGame: Boolean(),
      }],
    });
  },
};

And you'll have

Example

You can try out react-request-hook right in your browser with the Codesandbox example.

The example folder contains a /components folder with different use cases, like infinite scrolling components, search input that triggers the API, and so on. It's currently a work in progress.

Acknowledgement

Thanks to @kentcdodds for making this implementation a lot easier to test. create-react-library for the initial setup and Grommet with its great components used in the examples.

License

MIT