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

swr-loader

v0.3.2

Published

ux-centric data loading and caching

Downloads

8

Readme

SWR Loader

SWR Loader is a ux-centric way for achieving stale-while-revalidate in stream-capable data loaders. With it, you can leverage the user’s browser cache or a server-side cache to serve stale data while fetching new data in the background. This is especially useful for slow connections or when the user is offline while browsing your app.

Getting Started

Install the package:

npm install swr-loader

Usage

Creating a SWR instance

import { createSWR } from 'swr-loader';

export const { swr, invalidate } = createSWR({
	cacheAdapter: createIDBAdapter({ dbName: 'stargaze', storeName: 'data_cache' }),
	afterSet: data => {
		console.log('Data has been set in the cache:', data);
	},
});

React-router example

Here’s an example of how you can cache filtered data.

import { makeLoader, useLoaderData } from 'react-router-typesafe';
import { swr } from './swr';

const loader = makeLoader(async () => {
    const searchParams = new URL(request.url).searchParams;
    const page = searchParams.get('page');
    const q = searchParams.get('q');

	return defer({
		posts: await swr({
			cacheKey: ['posts', 'list', JSON.stringify({search, q})],
			fetchFn: () => getPosts({search, q})
			maxAge: 5 * 1000, // 5 seconds
			onError: 'serve-stale', // serve stale data if there is an error fetching new data, e.g.: internet is down
		}),
	});
});

// automatically handles cached data, loading states, and errors, obeys `onError` behaviour
import { SWR } from "swr-loader/react";

const Component = () => {
const { posts } = useLoaderData<typeof loader>();

    return <SWR
                data={posts}
                // will render when there is no cache and no data laoded yet
                loadingElement={<PostsSkeleton/>}
                // will render if there’s an error loading the data and there is no cache
                errorElement={<ErrorView heading="Error loading matches" />}
    			>
    				{posts => <ul>{posts.map(posts => <li key={post.id}>{post.title}</li>)}</ul>}
            </SWR>

}

Note You will have to await swr so that the ui-blocking part can be resolved (the cache) prior to rendering, but the fresh data will still be sent as an unfulfilled promise.

See the full example here.

Invalidating the cache

You can use invalidation as part of actions or simply call it in your event handlers, if your app is not server-side rendered.

import { invalidate } from './swr';

// invalidates only the posts list for page 1
invalidate(['posts', 'list', JSON.stringify({ page: '1', q: '' })]);

// invalidates all posts in listed
invalidate(['posts', 'list']);

API

createSWR

| Property | Type | Description | | -------------- | ------------------------------------------------- | ----------------------------------------------------- | | cacheAdapter | CacheAdapter | The cache adapter to use for storing data. | | beforeGet | (params: CacheAdapterFnParams) => Promise<void> | A function to run before getting data from the cache. | | afterGet | (data: unknown) => Promise<void> | A function to run after getting data from the cache. | | beforeSet | (params: CacheAdapterFnParams) => Promise<void> | A function to run before setting data in the cache. | | afterSet | (data: unknown) => Promise<void> | A function to run after setting data in the cache. |

Adapters

IndexedDB

Stores cached data in IndexedDB, has wide browser support. Client-side only, as IndexedDB is not available in server environments.

import { createIDBAdapter } from 'swr-loader/adapters/idb';
import { createSWR } from 'swr-loader';

export const { swr, invalidate } = createSWR({
	cacheAdapter: createIDBAdapter({ dbName: 'stargaze', storeName: 'data_cache' });
});

Memory

Stores cached data in a declared Map variable within closure-scope. Client-side only, as closure scope cannot be shared by server and client environments.

import { createMemoryAdapter } from 'swr-loader/adapters/memory';
import { createSWR } from 'swr-loader';

export const { swr, invalidate } = createSWR({
	cacheAdapter: createIDBAdapter({ dbName: 'stargaze', storeName: 'data_cache' }),
});

Redis

Coming Soon

LocalStorage / SessionStorage

Coming Soon