Package Exports
- react-fetch-hook
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (react-fetch-hook) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
react-fetch-hook
React hook, which allows you to conveniently work with fetch. Good Flow support.
Installation
Install it with yarn:
yarn add react-fetch-hookOr with npm:
npm i react-fetch-hook --saveUsage
useFetch hook accepts the same arguments as fetch function.
import React from "react";
import { useFetch } from "react-fetch-hook";
const Component = () => {
const { isLoading, data } = useFetch("https://swapi.co/api/people/1");
return isLoading ? (
<div>Loading...</div>
) : (
<UserProfile {...data} />
);
};
You can pass any fetch options:
const { isLoading, data } = useFetch("https://swapi.co/api/people/1", {
method: "get",
headers: {
Accept: "application/json, application/xml, text/plain, text/html, *.*",
"Content-Type": "application/json; charset=utf-8"
}
});
Custom formatter
You can pass formatter prop for using custom formatter function. Default is used response => response.json() formatter.
const { isLoading, data } = useFetch("https://swapi.co/api/people/1", {
formatter: (response) => response.text()
});
Prevent call fetch
For prevent call fetch you can pass depends prop:
const {authToken} = useContext(authTokenContext);
const [someState, setSomeState] = useState(false);
const { isLoading, data } = useFetch("https://swapi.co/api/people/1", {
depends: [!!authToken, someState] //don't call request, if haven't authToken and someState: false
});
Motivation: you can apply hooks only at top level of function.
Calling hooks inside if or for statements, or change count of hooks may throw React error.
// Potential сrash, because may call different count of hooks:
const {authToken} = useContext(authTokenContext);
if (!authToken) {
return null;
}
const { isLoading, data } = useFetch("https://swapi.co/api/people/1");