Minimal React hook that wraps a fetch request to a JSON HTTP service.
Using npm:
npm i use-http-service --save
Using yarn:
yarn add use-http-service
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
// ...
}
};
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)
- Andrea Marino - (marinoandrea)
See also the list of contributors who participated in this project.