ProductPromotion
Logo

React.JS

made by https://0x3d.site

GitHub - ilyalesik/react-fetch-hook: React hook for conveniently use Fetch API
React hook for conveniently use Fetch API. Contribute to ilyalesik/react-fetch-hook development by creating an account on GitHub.
Visit Site

GitHub - ilyalesik/react-fetch-hook: React hook for conveniently use Fetch API

GitHub - ilyalesik/react-fetch-hook: React hook for conveniently use Fetch API

react-fetch-hook

CircleCI npm version npm downloads

React hook for conveniently use Fetch API.

  • Tiny (556 B). Calculated by size-limit
  • Both Flow and TypeScript types included
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} />
  );
};

useFetch accepts the same arguments as fetch function.

Installation

Install it with yarn:

yarn add react-fetch-hook

Or with npm:

npm i react-fetch-hook --save

Usage

Custom formatter

Default is response => response.json() formatter. You can pass custom formatter:

const { isLoading, data } = useFetch("https://swapi.co/api/people/1", {
    formatter: (response) => response.text()
});

Error handling

The useFetch hook returns an error field at any fetch exception. The error field extends Error and has status and statusText fields equal to Response.

...

const Component = () => {
  const { isLoading, data, error } = useFetch("https://swapi.co/api/people/1");

  if (error) {
    return <div>
      <p>Code: ${error.status}</p>
      <p>Message: ${error.statusText}</p>
    </div>
  }
 
  ...
};

Multiple requests

Multiple useFetch in the same file/component supported:

const result1 = useFetch("https://swapi.co/api/people/1");
const result2 = useFetch("https://swapi.co/api/people/2");

if (result1.isLoading && result2.isLoading) {
  return <div>Loading...</div>;
}  

return <div>
    <UserProfile {...result1.data} />
    <UserProfile {...result2.data} />
</div>

Depends

The request will not be called until all elements of depends array be truthy. Example:

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 OR someState: false
});

See example.

Re-call requests

If any element of depends changed, request will be re-call. For example, you can use react-use-trigger for re-call the request:

import createTrigger from "react-use-trigger";
import useTrigger from "react-use-trigger/useTrigger";

const requestTrigger = createTrigger();

export const Subscriber = () => {  
    const requestTriggerValue = useTrigger(requestTrigger);
    
    const { isLoading, data } = useFetch("https://swapi.co/api/people/1", {
        depends: [requestTriggerValue]
    });
  
    return <div />;
}

export const Sender = () => { 
    return <button onClick={() => {
        requestTrigger() // re-call request
    }}>Send</button>
}

usePromise

For custom promised function.

import React from "react";
import usePromise from "react-fetch-hook/usePromise";
import callPromise from "..."

const Component = () => {
  const { isLoading, data } = usePromise(() => callPromise(...params), [...params]);

  return isLoading ? (
    <div>Loading...</div>
  ) : (
    <UserProfile {...data} />
  );
};

Examples

  • Basic - Just fetch data with useFetch.
  • Depends - Usage depends option for refresh query.
  • Pagination - Usage usePaginationRequest for infinite scroll implementation.

API

useFetch

Create a hook wrapper for fetch call.

useFetch(
    path: RequestInfo,
    options?: {
        ...RequestOptions,
        formatter?: Response => Promise
        depends?: Array<boolean>
    },
    specialOptions?: {
        formatter?: Response => Promise
        depends?: Array<boolean>
    }
): TUseFetchResult

where TUseFetchResult is:

{
    data: any,
    isLoading: boolean,
    error: any
}

RequestInfo, RequestOptions is fetch args.

usePromise

usePromise<T, I: $ReadOnlyArray<mixed>>(
    callFunction: ?(...args: I) => Promise<T>,
    ...inputs: I
): TUsePromiseResult<T>

where TUsePromiseResult<T> is

type TUsePromiseResult<T> = {
    data: ?T,
    isLoading: boolean,
    error: mixed
}

Experimental: usePaginatedRequest

⚠️ Warning: this method is experimental, API can be changed.

Create a paginated request.

usePaginatedRequest = <T>(
    request: (params: { limit: number, offset: number }) => Promise<Array<T>>,
    limit: number,
    ...depends: Array<any>
): {
    data: Array<T>,
    loadMore?: () => mixed,
    hasMore: boolean
};

Who Uses react-fetch-hook

Open Source projects

Companies

See more

More Resources
to explore the angular.

mail [email protected] to add your project or resources here 🔥.

Related Articles
to learn about angular.

FAQ's
to learn more about Angular JS.

mail [email protected] to add more queries here 🔍.

More Sites
to check out once you're finished browsing here.

0x3d
https://www.0x3d.site/
0x3d is designed for aggregating information.
NodeJS
https://nodejs.0x3d.site/
NodeJS Online Directory
Cross Platform
https://cross-platform.0x3d.site/
Cross Platform Online Directory
Open Source
https://open-source.0x3d.site/
Open Source Online Directory
Analytics
https://analytics.0x3d.site/
Analytics Online Directory
JavaScript
https://javascript.0x3d.site/
JavaScript Online Directory
GoLang
https://golang.0x3d.site/
GoLang Online Directory
Python
https://python.0x3d.site/
Python Online Directory
Swift
https://swift.0x3d.site/
Swift Online Directory
Rust
https://rust.0x3d.site/
Rust Online Directory
Scala
https://scala.0x3d.site/
Scala Online Directory
Ruby
https://ruby.0x3d.site/
Ruby Online Directory
Clojure
https://clojure.0x3d.site/
Clojure Online Directory
Elixir
https://elixir.0x3d.site/
Elixir Online Directory
Elm
https://elm.0x3d.site/
Elm Online Directory
Lua
https://lua.0x3d.site/
Lua Online Directory
C Programming
https://c-programming.0x3d.site/
C Programming Online Directory
C++ Programming
https://cpp-programming.0x3d.site/
C++ Programming Online Directory
R Programming
https://r-programming.0x3d.site/
R Programming Online Directory
Perl
https://perl.0x3d.site/
Perl Online Directory
Java
https://java.0x3d.site/
Java Online Directory
Kotlin
https://kotlin.0x3d.site/
Kotlin Online Directory
PHP
https://php.0x3d.site/
PHP Online Directory
React JS
https://react.0x3d.site/
React JS Online Directory
Angular
https://angular.0x3d.site/
Angular JS Online Directory