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

storeact

v3.0.0

Published

Zero-configuration store for React. One API rule them all

Downloads

20

Readme

Storeact

Zero-configuration store for React. One API rule them all.

Installation

npm i storeact --save

Get started

ES2015+ and Typescript:

import storeact from "storeact";

Example

Let's make an increment/decrement simple application with React:

First, create your store. This is where your application state will live:

const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const CounterStore = () => {
  let count = 0;
  return {
    state() {
      return count;
    },
    increase() {
      count++;
    },
    decrease() {
      count--;
    },
    async increaseAsync() {
      await delay(1000);
      this.increase();
    },
  };
};

The store is just pure function, we define some APIs and export count value via state() method

Now create your component. With Storeact your component can focus 100% on the UI and just call the actions that will automatically update the state:

const store = storeact(CounterStore);
function App() {
  const count = store.select();
  const { increase, decrease, increaseAsync } = store;

  return (
    <div className="App">
      <h1>{count}</h1>
      <div>
        <button onClick={() => increase()}>Increase</button>
        <button onClick={() => decrease()}>Decrease</button>
        <button onClick={() => increaseAsync()}>Increase Async</button>
      </div>
    </div>
  );
}

Storeact 's cool features

  1. Simple setup
  2. Simple API (only one)
  3. Store definition is pure function
  4. Less boilerplate
  5. Readability
  6. Configurable
  7. Easy to test
  8. Asynchronous action
  9. Future actions awaiting
  10. High performance
  11. Compatible with Immutable JS

Advanced Usages

Using action context

When an action is dispatching, storeact creates a task for each action call then pass that task as second argument of action. Using action task to control execution flow more easily.

Delay execution using task.delay(ms)

const Store = () => {
  let count = 0;

  return {
    increase() {
      count++;
    },
    async increaseAsync(payload, task) {
      await task.delay(1000);
      this.increase();
    },
  };
};

Using task.cancelOn(...cancelActions)

const Store = () => {
  return {
    cancel() {},
    async search(payload, task) {
      task.cancelOn(this.cancel);
      await task.delay(3000);
      if (task.cancelled()) return;
      // update state logic here
    },
  };
};

Using task.debounce(ms)

You can use debounce to wait certain amount of time before next execution block

const Store = () => {
  return {
    cancel() {},
    async search(payload, task) {
      await task.debounce(500);
      // update state logic here
    },
  };
};

Wait for future action dispatching

const Store = () => {
  return {
    async startDataFetching() {
      const data = await fetch("api");
      this.dataFetched(data);
    },
    dataFetched() {},
    async search(payload, task) {
      this.startDataFetching();
      // wait until dataFetched action dispatched
      const data = await task.when(this.dataFetched);
      // do something
    },
  };
};

You can improve above example with cancellable searching logic

const Store = () => {
  return {
    async startDataFetching() {
      const data = await fetch("api");
      this.dataFetched(data);
    },
    dataFetched() {},
    cancel() {},
    async search(term, task) {
      // search progress will be cancelled if cancel action dispatched
      task.cancelOn(this.cancel);
      await task.debounce(500);
      this.startDataFetching(term);
      // wait until dataFetched action dispatched
      const data = await task.when(this.dataFetched);
      // do something
    },
  };
};

Handling async data loading

You can use AsyncValue to handle async data loading easily

const TodoStore = ({ async }) => {
  // create async value object with empty array as default value
  const list = async([]);

  return {
    init(task) {
      // start data loading
      task.mutate(list, fetch("todo-api"));
    },
    state() {
      // return todos state is promise
      return { todos: list.promise };
    },
  };
};

In React component, to retrieve promised value we use selector util

const store = storeact(TodoStore);
const TodoCount = () => {
  const count = store.select((state, util) => {
    return util.value(state.todos).length;
  });
  return <h1>Todos ({count})</h1>;
};

const App = () => {
  return (
    <React.Suspense fallback="Loading...">
      <TodoCount />
    </React.Suspense>
  );
};

A "Loading..." message will show if todos promise still not fulfilled

util.loadable()

Using util.loadable() to retrieve Loadable object to render loading progress manually

const store = storeact(TodoStore);
const TodoCount = () => {
  const loadable = store.select((state, util) => {
    return util.loadable(state.todos);
  });
  if (loadable.state === "loading") return <div>Loading...</div>;
  if (loadable.state === "hasError")
    return <div>Oops, something went wrong. {loadable.error.message}</div>;
  // loadable.state === 'hasValue'
  return <h1>Todos ({count})</h1>;
};

Real World Examples

  1. Counter
  2. Shopping cart
  3. Shopping cart with code splitting for store