This package has been deprecated

Author message:

Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.

use-http-service
TypeScript icon, indicating that this package has built-in type declarations

1.3.1 • Public • Published

use-http-service

Build Status npm version codecov

Minimal React hook that wraps a fetch request to a JSON HTTP service.

Installation

Using npm:

npm i use-http-service --save

Using yarn:

yarn add use-http-service

Usage

You can import the hook as follows:

import useHttpService from "use-http-service";

The hook has to be called inside the body of a React functional component:

const [requestState, callApi] = useHttpService({
  url: "https://someapi.com/resource",

  // all values below are optional
  method: "PUT", // defaults to 'GET'
  credentials: "include", // possible values: "include" | "omit" | "same-origin"
  keepalive: false,
  mode: "cors", // possible values:  "cors" | "navigate" | "no-cors" | "same-origin"
  redirect: "follow", // possible values: "error" | "follow" | "manual"
  headers: {
    Authorization: "Bearer a.jwt.token",
    // `Content-Type` and `Accept` are automatically
    // set to `application/json`
  },
});

The callApi function is an async function that takes the body of your request (if needed) as an argument and returns a Result object:

const handleApiRequest = async (body) => {
  const res = await callApi(body);

  if (res.isOk) {
    const { data } = res;
    // use response body
    // ...
  } else {
    const { error } = res;
    // use error response body
    // ...
  }
};

Examples

Usage with JavaScript:

  • simple button click POST request (jsx)

  • useEffect GET request (jsx)

  • error handling in useEffect GET request (jsx)

  • using response data (jsx)

Usage with TypeScript:

  • simple button click POST request (tsx)

Authors

See also the list of contributors who participated in this project.

Package Sidebar

Install

npm i use-http-service

Weekly Downloads

5

Version

1.3.1

License

MIT

Unpacked Size

13.8 kB

Total Files

6

Last publish

Collaborators

  • marinoandrea