mauricedb / use-abortable-fetch

React hook that does a fetch and aborts when the components is unloaded or a different request is made

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

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

use-abortable-fetch

Build Status

React hook that does a fetch and aborts when the components is unloaded or a new fetch request is started.

Installation

npm install use-abortable-fetch or yarn add use-abortable-fetch

Example usage:

import React from 'react';
import useAbortableFetch from 'use-abortable-fetch';

const ChuckNorrisJoke = () => {
  const { data, loading, error, abort } = useAbortableFetch(
    '//api.icndb.com/jokes/random/?limitTo=[nerdy]&escape=javascript'
  );

  if (loading) return <div>Loading...</div>;
  if (error) return <div>Error: {error.message}</div>;
  if (!data) return null;

  return <div>Joke: {data.value.joke}</div>;
};

export default ChuckNorrisJoke;

See this CodeSandbox for a running example.

About

React hook that does a fetch and aborts when the components is unloaded or a different request is made

https://www.npmjs.com/package/use-abortable-fetch

License:MIT License


Languages

Language:TypeScript 58.4%Language:JavaScript 37.5%Language:HTML 4.2%