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

preact-fetching

v1.0.0

Published

Preact hooks for asynchronous data fetching

Downloads

85

Readme

Preact Fetching

Preact hooks for asynchronous data fetching.

Features

  • Promise-based data fetching. Unopinionated about the source of your data.
  • Small bundle size. Less than 0.5kb minified and gzipped.
  • TypeScript support. Respects the resolved type of your fetcher implementation.
  • Configurable global cache. All components share the same data by distinct keys.
  • Conditional data fetching. Supports advanced use-cases like form submission.

Example

import { useQuery } from 'preact-fetching';

function GitHubStars({ owner, repo }) {
	const { isLoading, isError, error, data } = useQuery(`${owner}/${repo}`, async () => {
		const response = await fetch(`https://api.github.com/repos/${owner}/${repo}`);
		const data = await response.json();
		return data.stargazers_count;
	});

	if (isError) {
		return `An error occurred! ${error.message}`;
	}

	if (isLoading) {
		return 'Loading...';
	}

	return `Count: ${data}`;
}

Installation

Install using NPM or Yarn:

npm install preact-fetching
yarn add preact-fetching

Usage

useQuery accepts two arguments:

  • A key to uniquely identify the data being fetched.
  • A function which fetches the data and returns either a promise or the resulting data.

Fetching

The fetching function will be called any time a component is mounted and there is not already a fetch in progress for that key. Requests are deduplicated if many components are mounted at the same time which reference the same data. Data is refetched if when future components are mounted using that same key, during which time the stale data will still be available.

Cache

The default cache behavior uses a simple Map object to reference cached values.

Cache Key

Because the default cache behavior uses a simple Map object, a key must be strictly equal on subsequent renders for a cache hit to occur (for example, using a string). For array or object values, you can consider one of the following:

Conditional Fetching

To prevent the fetch behavior based on some condition, pass a nullish (null or undefined) value as the key. If a nullish value is passed as the key, fetching will not occur.

API

useQuery

function useQuery<Data>(
	key: any,
	fetcher: () => Data | Promise<Data>,
): LoadingResult<Data> | SuccessResult<Data> | ErrorResult<Data> | IdleResult<Data>;

Triggers a new fetch request as appropriate and returns a result of the current status.

CacheContext

let CacheContext: import('preact').Context<
	MapLike<
		any,
		CacheLoadingEntry<any> | CacheSuccessEntry<any> | CacheErrorEntry<any> | CacheIdleEntry<any>
	>
>;

Context serving as cache state container. For most usage, you shouldn't need to interface with the context object, but in advanced use-cases you can use this to substitute or scope caches.

Project Goals and Non-Goals

Goals:

  • Lack of configurability as a feature, preferring smart defaults and a minimal-but-flexible API over a multitude of settings.
  • Efficiency in bundle size, performance, and cache invalidations. Micro-optimizations and code golf are welcome.

Non-goals:

  • Feature parity with similar libraries (swr, react-query, etc.).

License

Copyright 2024 Andrew Duthie

Released under the MIT License. See LICENSE.md.