Install

npm
npm i use-any-hook

Description

The useFetch hook simplifies the process of fetching data from an API by handling the loading, success, and error states. It is particularly useful for fetching data in functional components without the need for additional state management. This hook automatically triggers the fetch operation when the component is mounted or when the URL changes.

Parameters

NameTypeDescription
urlstringThe URL from which to fetch data. This should be a valid endpoint returning data.

Return Values

NameTypeDescription
dataanyThe data returned from the API. This will be null until the fetch operation is successful.
loadingbooleanA boolean indicating whether the fetch operation is in progress.
erroranyThe error encountered during the fetch operation, if any. This will be null if no error occurs.

Example

useFetch.example.tsx
import { useFetch } from "use-any-hook";

function MyComponent() {
  const [data, loading, error] = useFetch("https://api.example.com/data");

  useEffect(() => {
    // Handle data when it is available
    if (data) {
      // Do something with the fetched data
    }
  }, [data]);

  return (
    <div>
      {loading ? "Loading..." : null}
      {error ? "Error: Unable to fetch data" : null}
      {data ? <div>Data: {data}</div> : null}
    </div>
  );
}