1.0.1 • Published 10 months ago

@iva-stasia/use-fetch-hook v1.0.1

Weekly downloads
-
License
ISC
Repository
github
Last release
10 months ago

useFetch React Hook

A simple React hook for handling data fetching.

Install

$ npm install @iva-stasia/use-fetch-hook

Usage example

You can see how this code works here.

import { useState } from 'react';
import useFetch from '@iva-stasia/use-fetch-hook';

const MAX_ADVICE_NUM = 200;

const getRandomNum = () => {
  return Math.floor(Math.random() * MAX_ADVICE_NUM);
};

const App = () => {
  const [query, setQuery] = useState(() => getRandomNum());

  const URL = 'https://api.adviceslip.com/advice/' + query;
  const { data, loading, error } = useFetch(URL);

  return (
    <>
      {loading && 'Loading...'}
      {error && 'Error!'}
      {data && data.slip.advice}
      <button onClick={() => setQuery(getRandomNum())}>New Advice</button>
    </>
  );
};

export default App;

API

Parameters:

ParameterTypeRequiredDescription
URLStringYesThe URL to fetch data from.

Returns

The hook returns an object that contains the following properties:

ParameterTypeDescription
dataany | undefinedThe fetched data if the fetch was successful, otherwise undefined.
loadingbooleanA value that represents whether a request is pending.
errorerror | undefinedThe error object if an error occurred during the fetch, otherwise undefined.