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

@custom-react-hooks/use-async

v1.4.19

Published

The `useAsync` hook simplifies the handling of asynchronous operations in React applications, such as data fetching or any other promise-returning functions. It provides a structured way to track the status and outcome of async operations.

Downloads

287

Readme

useAsync Hook

The useAsync hook simplifies the handling of asynchronous operations in React applications, such as data fetching or any other promise-returning functions. It provides a structured way to track the status and outcome of async operations.

Features

  • Automated Execution: Optionally executes the async function automatically on component mount.
  • Manual Execution: Provides a function to manually trigger the async operation.
  • Status and Error Tracking: Tracks the status of the async operation and captures any errors.
  • SSR Compatibility: Safe for server-side rendering, with checks to prevent automatic execution on the server.
  • Value Management: Manages the value returned from the async operation.

Installation

Choose and install individual hooks that suit your project needs, or install the entire collection for a full suite of utilities.

Installing Only Current Hooks

npm install @custom-react-hooks/use-async

or

yarn add @custom-react-hooks/use-async

Installing All Hooks

npm install @custom-react-hooks/all

or

yarn add @custom-react-hooks/all

Usage

import React, { useState } from 'react';
import { useAsync } from '@custom-react-hooks/all';

const fetchData = async (endpoint) => {
  const response = await fetch(endpoint);
  if (!response.ok) {
    throw new Error(`Failed to fetch from ${endpoint}`);
  }
  return response.json();
};

const AsyncComponent = () => {
  const [endpoint, setEndpoint] = useState('');
  const [simulateError, setSimulateError] = useState(false);
  const { execute, status, value: data, error } = useAsync(() => fetchData(endpoint), false);

  const handleFetch = () => {
    if (simulateError) {
      setEndpoint('https://jsonplaceholder.typicode.com/todos/1');
    }
    execute();
  };

  return (
    <div>
      <input
        type="text"
        value={endpoint}
        onChange={(e) => setEndpoint(e.target.value)}
        placeholder="Enter API endpoint"
      />
      <button onClick={handleFetch}>Fetch Data</button>
      <div>
        <label>
          <input
            type="checkbox"
            checked={simulateError}
            onChange={() => setSimulateError(!simulateError)}
          />
          Simulate Error
        </label>
      </div>

      {status === 'pending' && <div>Loading...</div>}
      {status === 'error' && <div>Error: {error?.message}</div>}
      {status === 'success' && (
        <div>
          <h3>Data:</h3>
          <pre>{JSON.stringify(data, null, 2)}</pre>
        </div>
      )}
    </div>
  );
};

export default AsyncComponent;

In this example, the useAsync hook is used to perform an asynchronous data fetch operation.

API Reference

Parameters

  • asyncFunction (Function): The asynchronous function to execute.
  • immediate (Boolean, optional): A boolean indicating whether the async function should be executed immediately on component mount. Defaults to false.

Returns

An object with the following properties:

  • execute (Function): A function to trigger the async operation.
  • status (String): The current status of the async operation (idle, pending, success, error).
  • value (Any): The value returned from the async operation.
  • error (Error | null): Any error that occurred during the execution.

Use Cases

  1. API Data Fetching: Fetching data from an API when a component mounts or based on user actions.

  2. Form Submission Handling: Managing asynchronous form submissions to a server, including loading states and error handling.

  3. Lazy Loading: Dynamically loading components or data based on certain conditions or user interactions.

  4. Web API Interactions: Simplifying the use of asynchronous Web APIs (like geolocation or camera access).

  5. File Uploads: Handling the asynchronous process of file uploads, including progress tracking and error management.

  6. Real-time Data Updates: Managing WebSocket connections or server polling for live data updates.

  7. Complex Calculations/Processing: Executing and managing state for asynchronous complex calculations, such as those using Web Workers.

  8. Third-party Service Integration: Facilitating interactions with asynchronous third-party services (e.g., payment gateways, social media APIs).

  9. Conditional Async Operations: Executing asynchronous tasks based on specific conditions or inputs.

  10. Sequencing Async Operations: Coordinating multiple dependent asynchronous operations in sequence.

Contributing

Contributions to enhance useAsync are highly encouraged. Feel free to submit issues or pull requests to the repository.