npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@bloodyaugust/use-fetch

v1.1.1

Published

A simple, safe fetch custom hook for React.

Downloads

987

Readme

@bloodyaugust/use-fetch

A simple, safe fetch custom hook for React. Why safe? There's a good chance you've seen this before:

Warning: Can’t perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.

This hook helps you avoid mutating state on components that are unmounted by providing you with the mounted state of the hook, and aborts in-flight requests on unmount.

Features

  • Safe: gives you the tools to avoid mutating state on unmounted components.
  • Simple: Just a hook! No Contexts were harmed (or used) in the source of this library.
  • Flexible: you get the response, the json, and of course the mounted state.
  • Configurable: turn off automatic json parsing for those one-off cases.
  • Provides a convenient Promise-based API.
  • Aborts in-flight requests automatically if unmounted.
  • Rejects Promise if the response indicates failure.
  • No dependencies aside from React.

Install

npm install @bloodyaugust/use-fetch
# or, if using yarn
yarn add @bloodyaugust/use-fetch

Usage

This example demonstrates how you might get some todos with useFetch while being sure you don't mutate state after your component is unmounted.

import React, { useEffect, useState } from "react";
import useFetch from "@bloodyaugust/use-fetch";

function TodoList() {
  const { execute } = useFetch();
  const [todos, setTodos] = useState([]);

  useEffect(() => {
    const getTodos = async () => {
      await execute("https://jsonplaceholder.typicode.com/todos/").then(
        ({ json, mounted }) => {
          if (mounted) {
            setTodos(json);
          }
        }
      );
    };

    getTodos();
  }, []);

  return (
    <div>
      {todos.map((todo) => {
        <span key={todo.id}>{todo.title}</span>;
      })}
    </div>
  );
}

API

Props

useFetch({
  noJSON: bool, // Set true if you want to skip JSON parsing (no json key will be provided to the promise chain)
});

Execute

execute is the function returned for invoking your fetch. It provides as consistent an API as it can, but there are some slight differences depending on if the request is successful, aborted, or failed for some other reason.

Parameters are the same as fetch.

success

useFetch('https://jsonplaceholder.typicode.com/todos/')
  .then({
    response, // The fetch Response object
    json, // The result of response.json() (not present if the noJSON prop was set)
    mounted // The mounted state of the hook
  } => {})

error with fetch (includes abort)

useFetch('https://jsonplaceholder.typicode.com/todos/')
  .catch({
    error // The Error object thrown by fetch
  } => {})

response indicates failure (!response.ok)

useFetch('https://jsonplaceholder.typicode.com/todos/')
  .catch({
    response,
    error, // new Error(`Request failed: ${response.status}`)
    mounted
  } => {})

Completed

completed is a ref returned from the hook to allow for determining the completion state of the fetch. It starts as false, but becomes true when the request completes for any reason (including abort).