2.0.0 • Published 5 years ago

@arthurdenner/use-fetch v2.0.0

Weekly downloads
-
License
MIT
Repository
github
Last release
5 years ago

@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

nametyperequireddescription
cacheKeystringnolocalStorage key to store the response
expiryTimenumbernoamount of time to cache the response
initialDataTyesinitial data for the hook
isJsonPbooleannoindicates if the URL returns JSONP data
optionsRequestInitnooptions accepted by the fetch API
urlstringyesURL to be fetched

Return

nametypedescription
abort() => voidcallback function to cancel the request
start() => voidcallback function to fire the request
dataTdata returned from the request
errorError | undefinederror occurred on the request
loadingbooleanindicates if the request is being made
canceledbooleanindicates if the request was canceled

Contributors

Thanks goes to these wonderful people (emoji key):

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

License

MIT © Arthur Denner