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-graph-state

v2.1.4

Published

SWR + graph-state

Downloads

101

Readme

swr-graph-state

swr-store + graph-state

NPM JavaScript Style GuideOpen in CodeSandbox

Install

yarn add graph-state swr-graph-state

Usage

import React, { Suspense } from 'react';
import {
  GraphDomain,
  useGraphNodeResource,
} from 'react-graph-state';
import { node } from 'graph-state';
import { swr } from 'swr-graph-state';

const API = 'https://dog.ceo/api/breed/';
const API_SUFFIX = '/images/random';

interface APIResult {
  message: string;
  status: string;
}

const dogBreed = node({
  get: 'shiba',
});

const dogAPI = swr<APIResult>({
  key: 'dogAPI',
  setup: ({ get }) => {
    const breed = get(dogBreed);
    return async () => {
      const response = await fetch(`${API}${breed}${API_SUFFIX}`);
      return (await response.json()) as APIResult;
    };
  },
  revalidateOnFocus: true,
  revalidateOnNetwork: true,
});

function DogImage(): JSX.Element {
  const data = useGraphNodeResource(dogAPI.resource);

  return <img src={data.message} alt={data.message} />;
}

function Trigger(): JSX.Element {
  return (
    <button
      type="button"
      onClick={() => {
        dogAPI.trigger();
      }}
    >
      Trigger
    </button>
  );
}

export default function App(): JSX.Element {
  return (
    <GraphDomain>
      <Trigger />
      <div>
        <Suspense fallback={<h1>Loading...</h1>}>
          <DogImage />
        </Suspense>
      </div>
    </GraphDomain>
  );
}

Features

Hydration

SWR node may present an initial data through options.initialData. This data is used only when the store finds an empty cache value. Initial data is also useful for opting-out of initial pending phase and providing a way for SSR pages to hydrate nodes.

const userDetails = swr({
  key: '/user/details',
  setup: () => () => getUserDetails(),
  initialData: prefetchedData,
});

Subscriptions

SWR nodes allows subscriptions to subscribe for cache updates. Subscribing returns a callback that allows unsubscribing to the cache updates.

// Local subscription
const unsubscribe = userDetails.subscribe((result) => {
  if (result.status === 'pending') {
    displaySkeleton();
  } else if (result.status === 'failure') {
    displayFallback();
  } else if (result.status === 'success') {
    displayUI(result.data);
  }
});

// global subscription
import { subscribe } from 'swr-graph-state';

const unsubscribe = subscribe('/user/details', (result) => {
  if (result.status === 'pending') {
    displaySkeleton();
  } else if (result.status === 'failure') {
    displayFallback();
  } else if (result.status === 'success') {
    displayUI(result.data);
  }
});

Manual Revalidation

SWR nodes have the methods mutate and trigger which allows manual revalidation of cached data. mutate overwrites the cached data while trigger prompts for a revalidation.

const userDetails = swr({
  key: '/user/details',
  setup: () => () => getUserDetails(),
});

userDetails.trigger();

userDetails.mutate({
  data: {
    name: 'John Doe',
    age: 16,
  },
  status: 'success',
});

Global Revalidation

SWR nodes share the same global cache, and can be prompted with a global manual revalidation. trigger and mutate are similar to node's node.trigger and node.mutate except that they accept the cache key first.

Stores subscribers may be notified (trigger does not guarantee a notification, while mutate guarantees a notification) for the cache update.

import { trigger, mutate } from 'swr-graph-state';

const userDetails = swr({
  key: '/user/details',
  get: () => getUserDetails(),
});

// ...
// Global trigger
trigger('/user/details');

// Or mutate
mutate('/user/details', {
  data: {
    name: 'John Doe',
    age: 16,
  },
  status: 'success',
});

Local Revalidation

SWR nodes can be manually revalidated by calling node.trigger or node.mutate.

  • node.trigger(shouldRevalidate = true): Triggers a revalidation from the given arguments. Arguments are passed to options.key to locate the cache.
  • node.mutate(result, shouldRevalidate = true): Mutates the cache with result. Cache is located based on the key generated from the arguments passed to options.key.
// Local revalidation
userDetails.trigger([userId]);

// is the same as 
trigger(`/user/${userId}`);

// Since userDetails yields the same key format.

Other features

Most features of swr-graph-state is adapted from swr-store so be sure to check it out. Options for both swr and swrFactory are also derived from it (with the exception of setup and key).

License

MIT © lxsmnsyc