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

@weedzcokie/store

v2.0.2

Published

Tiny store management

Downloads

34

Readme

@weedzcokie/store

npm (scoped) npm bundle size (scoped)

Usage

A full example can be found in example.

store.ts:

// Setup store
import { createStore } from "@weedzcokie/store";
type StoreType = {
    counter: number
};

const store = createStore<StoreType>({
    counter: 0
});
type StoreKeys = keyof StoreType;

export const Store = store.Store;

// Use store
store.subscribe("counter", count => {
    console.log(`current count: ${count}`);
});

store.updateStore({
    counter: 1
});

Preact component

import { createStore, PartialStoreListener } from "@weedzcokie/store";

// Create store as in `store.ts`.

export abstract class StoreComponent<P = unknown, S = unknown> extends Component<P, S> {
    listeners: Array<() => void> = [];

    listen<T extends StoreKeys>(key: T, cb: PartialStoreListener<StoreType, T> = () => this.forceUpdate()) {
        this.listeners.push(store.subscribe(key, cb));
    }

    componentWillUnmount() {
        for (const unsubscribe of this.listeners) {
            unsubscribe();
        }
    }
}

Can now be used as:

import { StoreComponent, Store, store } from "./store";
export default class App extends StoreComponent {
    componentDidMount() {
        this.listen("counter");
    }
    // ...
    
    // If you need to use `componentWillUnmount`, do not forget to call `super.componentWillUnmount()`
    componentWillUnmount() {
        super.componentWillUnmount();
        // ...
    }

    // store is available from the exported Store variable.
    render() {
        return (
            <p>Current count: {Store.counter}</p>
            <button onClick={() => store.updateStore({counter: Store.counter + 1})}>Increment count</button>
        );
    }
}

Hooks

Or using hooks:

import { Store, store } from "./store";

// Create store as in `store.ts`.

export function useStore<T extends StoreKeys>(keys: T[]) {
    const [s, set] = useState(false);

    useEffect(() => {
        const update = () => set(current => !current);
        const listeners = keys.map(key => store.subscribe(key, update));

        return () => {
            for (const unsubscribe of listeners) {
                unsubscribe()
            }
        }
    }, []);

    return { data: Store as Pick<StoreType, T> };
}

function App() {
    useStore(["counter"]);

    return (
        <p>Current count: {Store.counter}</p>
        <button onClick={() => store.updateStore({counter: Store.counter + 1})}>Increment count</button>
    );
}

Hooks with "initializers"

./store.ts:

type StoreType = {
    user: null | StoredUser
    favorites: Set<number>
}
type StoreKeys = keyof StoreType;

const store = createStore<StoreType>({
    user: null,
    favorites: new Set(),
});

const initFnLoaders: Map<string, Promise<unknown>> = new Map();
const initFn: Partial<{
    [K in StoreKeys]: () => void
}> = {
    user: async () => {
        // Check if logged in
        const user = localStorage.getItem("user");
        if (user) {
            const res = await fetch("/api/auth");

            if (!res || res.status !== 200) {
                localStorage.removeItem("user");
                store.updateStore({user: null});
                return;
            }

            store.updateStore({user: user})
        }
    },
}

export function useStore<T extends StoreKeys>(keys: T[]) {
  const [_s, set] = useState(false);
  const [loading, setLoading] = useState(true);
  useEffect(() => {
    const propsToLoad: Set<string> = new Set();
    const update = () => set(current => !current);
    const listeners = keys.map((key) => store.subscribe(key, update));

    for (const key of keys) {
      let promise = initFnLoaders.get(key);
      if (promise) {
        propsToLoad.add(key);
        promise.then(() => {
          propsToLoad.delete(key);
          setLoading(!!propsToLoad.size);
        });
      }

      const fn = initFn[key];
      if (fn) {
        propsToLoad.add(key);
        promise = fn().then(() => {
          initFnLoaders.delete(key);
          propsToLoad.delete(key);
          setLoading(!!propsToLoad.size);
        });

        initFnLoaders.set(key, promise);

        delete initFn[key];
      }
    }

    if (propsToLoad.size === 0) {
      setLoading(false);
    }

    return () => {
      for (const unsubscribe of listeners) {
        unsubscribe();
      }
    };
  }, []);

  return { loading, data: Store as Pick<StoreType, T> };
}

./profile.tsx:

export default ProfilePage() {
    const {loading, data} = useStore(["user"]);
    if (loading || !data.user) {
        return null;
    }

    return <Profile />
}