react-hooks-fetch

Minimal data fetching library with React Suspense

Usage no npm install needed!

<script type="module">
  import reactHooksFetch from 'https://cdn.skypack.dev/react-hooks-fetch';
</script>

README

react-hooks-fetch

CI npm size discord

Minimal data fetching library with React Suspense

Introduction

This library provides a React hook useFetch for any async functions. It utilizes React Suspense and requires to create a store in advance with createFetch. The API is designed to force fetching data before rendering.

Project status: Experimental. We need to collect feedbacks.

Install

npm install react-hooks-fetch

Usage

import React, { Suspense } from 'react';
import { ErrorBoundary } from 'react-error-boundary';

import { createFetch, useFetch } from 'react-hooks-fetch';

// 1️⃣
// Create a store with an async function.
// The async function can take one input argument.
// The input value becomes the "key" of cache.
// By default, keys are compared with strict equal `===`.
const store = createFetch(async (userId) => {
  const res = await fetch(`https://reqres.in/api/users/${userId}?delay=3`);
  const data = await res.json();
  return data;
});

// 2️⃣
// We need to start fetching somewhere before rendering.
// If we allow `undefined` value for the initial render,
// this can be omitted.
store.prefetch('1');

// 3️⃣
// Define a component to use store.
// The `refetch` function take the input argument,
// and it will start fetching before rendering.
const Main = () => {
  const { result, refetch } = useFetch(store, '1');
  const handleClick = () => {
    refetch('2');
  };
  return (
    <div>
      <div>First Name: {result.data.first_name}</div>
      <button type="button" onClick={handleClick}>Fetch user 2</button>
    </div>
  );
};

// 4️⃣
// The outer component should have ErrorBoundary and Suspense boundary.
const App = () => (
  <ErrorBoundary fallback={<h1>Error</h1>}>
    <Suspense fallback={<span>Loading...</span>}>
      <Main />
    </Suspense>
  </ErrorBoundary>
);

API

createFetch

create fetch store

Parameters

  • fetchFunc FetchFunc<Input, Result>
  • options Options<Input, Result>?

Examples

import { createFetch } from 'react-hooks-fetch';

const fetchFunc = async (userId) => {
  const res = await fetch(`https://reqres.in/api/users/${userId}?delay=3`));
  const data = await res.json();
  return data;
};
const store = createFetch(fetchFunc);
store.prefetch('1');

useFetch

useFetch hook

Parameters

  • store FetchStore<Input, Result>
  • initialInput Input?

Examples

import { useFetch } from 'react-hooks-fetch';

const { result, refetch } = useFetch(store, initialInput);

Examples

The examples folder contains working examples. You can run one of them with

PORT=8080 npm run examples:01_minimal

and open http://localhost:8080 in your web browser.

You can also try them in codesandbox.io: 01 02 03

Blogs

See History for previous implementations.