use-http-service

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",
method: "PUT",
credentials: "include",
keepalive: false,
mode: "cors",
redirect: "follow",
headers: {
Authorization: "Bearer a.jwt.token",
},
});
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;
} else {
const { error } = res;
}
};
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.