Skip to content
React hook for conveniently use Fetch API
JavaScript
Branch: master
Clone or download
Latest commit 2a2ca59 Oct 1, 2019
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
.github Update FUNDING.yml May 26, 2019
examples Add examples root readme Jul 10, 2019
jest Restore pre-commit hook May 19, 2019
test Make isLoading true by default #13 Oct 1, 2019
utils Rename folders: src -> utils, tests -> test May 22, 2019
.babelrc Add pagination example Jun 17, 2019
.eslintignore Fix receive { isLoading: true } when pass depends with false value Jun 12, 2019
.flowconfig Add useFetch, usePromise hooks Dec 18, 2018
.gitignore Init repository Dec 18, 2018
.npmignore Configure build Dec 18, 2018
.travis.yml Remove npm update from travis config Apr 27, 2019
CODE_OF_CONDUCT.md Create CODE_OF_CONDUCT.md Apr 5, 2019
LICENSE Create LICENSE Apr 4, 2019
README.md Make isLoading true by default #13 Oct 1, 2019
index.d.ts Update ts typings May 22, 2019
index.js Fix receive { isLoading: true } when pass depends with false value Jun 12, 2019
index.js.flow Update flow typings May 29, 2019
package-lock.json Bump lodash from 4.17.11 to 4.17.14 Jul 12, 2019
package.json v1.7.1 Oct 1, 2019
tsconfig.json Add TS typings May 8, 2019
usePaginatedRequest.d.ts Add ...depends param to usePaginationRequest typings Jul 10, 2019
usePaginatedRequest.js Implement flush request after change depends at usePaginatedRequest Jul 10, 2019
usePaginatedRequest.js.flow Add ...depends param to usePaginationRequest typings Jul 10, 2019
usePromise.d.ts Update ts typings May 22, 2019
usePromise.js Make isLoading true by default #13 Oct 1, 2019
usePromise.js.flow Update flow typings May 29, 2019

README.md

react-fetch-hook

Build Status npm version npm downloads

React hook for conveniently use Fetch API.

  • Tiny (397 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()
});

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 and 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
};

Sponsored

Sponsored by Lessmess
You can’t perform that action at this time.