All Projects → ilyalesik → React Fetch Hook

ilyalesik / React Fetch Hook

Licence: mit
React hook for conveniently use Fetch API

Programming Languages

javascript
184084 projects - #8 most used programming language
typescript
32286 projects
flowtype
47 projects

Projects that are alternatives of or similar to React Fetch Hook

Node Fetch
A light-weight module that brings the Fetch API to Node.js
Stars: ✭ 7,176 (+2417.89%)
Mutual labels:  hacktoberfest, fetch, fetch-api
React Ufo
🛸 react-ufo - A simple React hook to help you with data fetching 🛸
Stars: ✭ 85 (-70.18%)
Mutual labels:  hooks, fetch, fetch-api
Nbstripout
strip output from Jupyter and IPython notebooks
Stars: ✭ 738 (+158.95%)
Mutual labels:  hacktoberfest, hooks
Redux Query
A library for managing network state in Redux
Stars: ✭ 1,055 (+270.18%)
Mutual labels:  hacktoberfest, fetch
fetch
A fetch API polyfill for React Native with text streaming support.
Stars: ✭ 27 (-90.53%)
Mutual labels:  fetch, fetch-api
React Infinite Scroll Hook
A simple hook to create infinite scroll list components
Stars: ✭ 151 (-47.02%)
Mutual labels:  hooks, fetch
React Table
⚛️ Hooks for building fast and extendable tables and datagrids for React
Stars: ✭ 15,739 (+5422.46%)
Mutual labels:  hooks, pagination
Usestatewithlayoutanimation
Abstraction for `React Native`'s `LayoutAnimation` and `useState`
Stars: ✭ 19 (-93.33%)
Mutual labels:  hacktoberfest, hooks
bestfetch
fetch ⭐️caching ⭐️deduplication
Stars: ✭ 44 (-84.56%)
Mutual labels:  fetch, fetch-api
mey
A react package that exports hooks for handling the request lifecycle.
Stars: ✭ 18 (-93.68%)
Mutual labels:  fetch, hooks
node-fetch-har
Generate HAR entries for requests made with node-fetch
Stars: ✭ 23 (-91.93%)
Mutual labels:  fetch, fetch-api
Tipple
A lightweight dependency-free library for fetching data over REST with React.
Stars: ✭ 133 (-53.33%)
Mutual labels:  hooks, fetch
fetch-wrap
extend WHATWG fetch wrapping it with middlewares
Stars: ✭ 21 (-92.63%)
Mutual labels:  fetch, fetch-api
Meteor Collection Hooks
Meteor Collection Hooks
Stars: ✭ 641 (+124.91%)
Mutual labels:  hacktoberfest, hooks
Vue Composable
Vue composition-api composable components. i18n, validation, pagination, fetch, etc. +50 different composables
Stars: ✭ 638 (+123.86%)
Mutual labels:  hooks, pagination
React Fetching Library
Simple and powerful API client for react 👍 Use hooks or FACCs to fetch data in easy way. No dependencies! Just react under the hood.
Stars: ✭ 561 (+96.84%)
Mutual labels:  hooks, fetch
Instagram Proxy Api
CORS compliant API to access Instagram's public data
Stars: ✭ 245 (-14.04%)
Mutual labels:  fetch, pagination
React Query
⚛️ Hooks for fetching, caching and updating asynchronous data in React
Stars: ✭ 24,427 (+8470.88%)
Mutual labels:  hooks, fetch
legible
the cleanest way to make http requests in js / node
Stars: ✭ 49 (-82.81%)
Mutual labels:  fetch, fetch-api
axios-endpoints
Axios endpoints helps you to create a more concise endpoint mapping with axios.
Stars: ✭ 41 (-85.61%)
Mutual labels:  fetch, 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

Sponsored

Sponsored by Lessmess
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].