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

v2.1.4

Published

Preact bindings for `graph-state`

Downloads

305

Readme

preact-graph-state

Preact bindings for graph-state

NPM JavaScript Style GuideOpen in CodeSandbox

Install

yarn add graph-state preact-graph-state
npm install graph-state preact-graph-state

Usage

Accessing a graph node

Graph nodes, by themselves, are meaningless. They needed a domain to begin computing. <GraphDomain> is a component that defines such domain where all graph nodes live.

import { GraphDomain } from 'preact-graph-state';

const messageNode = node({
  get: 'Hello World',
});

function App() {
  return (
    <GraphDomain>
      {/* children */}
    </GraphDomain>
  );
}

There are also 8 hooks:

  • useGraphNodeValue: reads a graph node's value. Subscribes to the graph node's state updates.
  • useGraphNodeDispatch: provides a callback that allows graph node's state mutation or runs set field.
  • useGraphNodeReset: provides a callback for resetting (recomputing) a graph node's value.
  • useGraphNodeState: a combination of useGraphNodeValue, useGraphNodeDispatch and useGraphNodeReset in a form of a tuple.
  • useGraphNodeHydrate: hydrates a node instance with a given initial state, then resets the node after commit. Useful for prefetched data.
  • useGraphNodeResource: treats the graph node as a valid Preact resource, suspending the component if the graph node's resource is pending.
  • useGraphNodeSnapshot: attaches a listener to the node for state updates.
  • useGraphNodeMutate: provides a callback that allows graph node's state mutation.
  • useGraphNodeSelector: similar to useGraphNodeValue, but allows transformation of received value and conditional re-rendering.

If one of these hooks are used to access a graph node, that graph node is registered within <GraphDomain> and creates a lifecycle.

Hooks

useGraphNodeValue

This is a Preact hook that reads the graph node's current state and subscribes to further state updates.

function Message() {
  const message = useGraphNodeValue(messageNode);

  return <h1>{ message }</h1>;
}
useGraphNodeDispatch

This is a Preact hook that returns a callback similar to setState that allows state mutation for the given graph node.

function MessageInput() {
  const setMessage = useGraphNodeDispatch(messageNode);

  const onChange = useCallback((e) => {
    setFahrenheit(Number.parseFloat(e.currentTarget.value));
  }, []);

  return (
    <input
      type="text"
      onChange={onChange}
    />
  );
}

If a graph node has a defined set function, useGraphNodeDispatch will not overwrite the graph node's state and thus, can accept any kind of value for dispatch. set will receive this value, allowing for custom graph node logic:

const countNode = node({
  get: 0,
});

const reducerNode = node({
  get: ({ get }) => get(countNode),
  set: ({ set }, action) => {
    switch (action) {
      case 'INCREMENT':
        set(countNode, get(countNode) + 1);
        break;
      case 'DECREMENT':
        set(countNode, get(countNode) - 1);
        break;
    }
  },
});

// ...
const dispatch = useGraphNodeDispatch(reducerNode);

// ...
dispatch('INCREMENT');
useGraphNodeReset

This is a hook that provides a callback for resetting a graph node.

const reset = useGraphNodeReset(countNode);

// ...
reset(); // resets countNode back to 0
useGraphNodeState

This is a hook that returns a tuple based on useGraphNodeValue, useGraphNodeDispatch and useGraphNodeReset.

const [count, setCount, reset] = useGraphNodeState(countNode);
useGraphNodeSnapshot

This is a hook that attaches a listener to a graph node and subscribes for state updates.

useGraphNodeSnapshot(node, (state) => {
  console.log('Received', state);
});
useGraphNodeMutate

This is a hook that returns a callback similar to setState that allows state mutation for the given graph node.

const setState = useGraphNodeMutate(node);

// Rewrite!
setState(newState);

// Derived
setState((prevState) => diff(prevState, newState));
useGraphNodeHydrate

USE WITH CAUTION Synchronously and silently mutates a graph node's state. This is only recommended for independent nodes as a form of lazy state hydration.

useGraphNodeHydrate(countNode, 100);
useGraphNodeSelector

Similar to useGraphNodeValue but allows transformation of received value and conditional re-rendering.

const name = useGraphNodeSelector(userNode, {
  getSnapshot: (value) => {
    return value.name;
  },
  shouldUpdate: (prev, next) => {
    return prev !== next;
  },
});
useGraphNodeResource

This is a hook that receives a valid graph node resource and suspends the component until the resource is successful. This may resuspend the component if the resource updates itself.

Graph Node Resources

Accessing a graph node resource using useGraphNodeValue returns an object which represents the Promise result.

function UserProfile() {
  const result = useGraphNodeValue(userResourceNode);

  if (result.status === 'pending') {
    return <h1>Loading...</h1>;
  }
  if (result.status === 'failure') {
    return <h1>Something went wrong.</h1>;
  }
  return <UserProfileInternal data={result.data} />;
}

There's also another hook called useGraphNodeResource which allows us to suspend the component until the resource is successful.

function UserProfileInternal() {
  const data = useGraphNodeResource(userResourceNode);

  return (
    <UserProfileContainer>
      <UserProfileName>{ data.name }</UserProfileName>
      <UserProfileDescription>{ data.description }</UserProfileDescription>
    </UserProfile>
  );
}

function UserProfile() {
  return (
    <ErrorBoundary fallback={<h1>Something went wrong.</h1>}>
      <Suspense fallback={<h1>Loading...</h1>}>
        <UserProfileInternal />
      </Suspense>
    </ErrorBoundary>
  );
}

License

MIT © lxsmnsyc