Flixow / fetch-suspense

A React hook compatible with React 16.6's Suspense component.

Home Page:https://www.npmjs.com/package/fetch-suspense

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

useFetch Tweet version minified size minzipped size downloads build

useFetch is a React hook that supports the React 16.6 Suspense component implementation.

The design decisions and development process for this package are outlined in the Medium article React Suspense with the Fetch API.

Install

  • npm install fetch-suspense --save or
  • yarn add fetch-suspense

Example

import useFetch from 'fetch-suspense';
import React, { Suspense } from 'react';

// This fetching component will be delayed by Suspense until the fetch request
//   resolves.
// The return value of useFetch will be the response of the server.
const MyFetchingComponent = () => {
  const data = useFetch('/path/to/api', { method: 'POST' });
  return 'The server responded with: ' + data;
};

// The App component wraps the asynchronous fetching component in Suspense.
// The fallback component (loading text) is displayed until the fetch request
//   resolves.
const App = () => {
  return (
    <Suspense fallback="Loading...">
      <MyFetchingComponent />
    </Suspense>
  );
};

Using a Custom Fetch API

If you don't want to rely on the global fetch API, you can create your own useFetch hook by importing the createUseFetch helper function.

import { createUseFetch } from 'fetch-suspense';
import myFetchApi from 'my-fetch-package';
import React, { Suspense } from 'react';

// Create a useFetch hook using one's own Fetch API.
// NOTE: useFetch hereafter refers to this constant, not the default export of
//   the fetch-suspense package.
const useFetch = createUseFetch(myFetchApi);

// This fetching component will be delayed by Suspense until the fetch request
//   resolves.
// The return value of useFetch will be the response of the server.
const MyFetchingComponent = () => {
  const data = useFetch('/path/to/api', { method: 'POST' });
  return 'The server responded with: ' + data;
};

// The App component wraps the asynchronous fetching component in Suspense.
// The fallback component (loading text) is displayed until the fetch request
//   resolves.
const App = () => {
  return (
    <Suspense fallback="Loading...">
      <MyFetchingComponent />
    </Suspense>
  );
};

About

A React hook compatible with React 16.6's Suspense component.

https://www.npmjs.com/package/fetch-suspense

License:MIT License


Languages

Language:TypeScript 91.6%Language:JavaScript 8.4%