@arthurdenner/use-fetch
TypeScript icon, indicating that this package has built-in type declarations

2.0.0 • Public • Published

@arthurdenner/use-fetch

npm All Contributors gzip size install size

React hook to fetch data with useful features.

Install

yarn add @arthurdenner/use-fetch
npm i @arthurdenner/use-fetch

Usage

import React from 'react';
import useFetch from '@arthurdenner/use-fetch';

function App() {
  const { data: users, error, loading } = useFetch({
    initialData: [],
    url: 'https://jsonplaceholder.typicode.com/users',
  });

  if (error) {
    console.log(error);
    return <div>An error occured!</div>;
  }

  if (loading) {
    return <div>Loading...</div>;
  }

  return (
    <div>
      <ul>
        {users.map(user => (
          <li>{user.name}</li>
        ))}
      </ul>
    </div>
  );
}

Features

  • TypeScript-friendly
  • JSONP support
  • localStorage cache support
    • You don't pass a cacheKey, the hash of the URL will be used
  • Abort request support (manually and when the component unmounts)

Config

name type required description
cacheKey string no localStorage key to store the response
expiryTime number no amount of time to cache the response
initialData T yes initial data for the hook
isJsonP boolean no indicates if the URL returns JSONP data
options RequestInit no options accepted by the fetch API
url string yes URL to be fetched

Return

name type description
abort () => void callback function to cancel the request
start () => void callback function to fire the request
data T data returned from the request
error Error | undefined error occurred on the request
loading boolean indicates if the request is being made
canceled boolean indicates if the request was canceled

Contributors

Thanks goes to these wonderful people (emoji key):

Arthur Denner
Arthur Denner

💻 🎨 📖 💡 🤔 🚧

This project follows the all-contributors specification. Contributions of any kind welcome!

License

MIT © Arthur Denner

Readme

Keywords

Package Sidebar

Install

npm i @arthurdenner/use-fetch

Weekly Downloads

0

Version

2.0.0

License

MIT

Unpacked Size

22.9 kB

Total Files

7

Last publish

Collaborators

  • arthurdenner