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

react-charm

v1.0.26

Published

Effortless state management

Downloads

63

Readme

react-charm

Counter App

import React from "react";
import { render } from "react-dom";
import { useStates, setState, dispatch } from "react-charm";

setState({ counter: 0 });

// create named action
const increase = ({ state }) => state.counter++;

const App = () => {
  // useCharm retrieves state selector list
  // then return array of [stateValue1, stateValue2, ...]
  const [counter] = useStates(state => state.counter);

  function handleClick() {
    dispatch(increase);
  }

  return (
    <>
      <h1>{counter}</h1>
      <button onClick={handleClick}>Increase</button>
    </>
  );
};

render(<App />, document.getElementById("root"));

Ajax Data Loading

import React from "react";
import { render } from "react-dom";
import { useStates, dispatch } from "react-charm";

const fetchEffect = ({ action }, url, onSuccess, onFailure) => {
  fetch(url)
    .then(res => res.json())
    .then(payload => {
      payload.message
        ? action(onFailure, payload.message)
        : action(onSuccess, payload);
    });
};

const loadDataSuccessAction = ({ state }, payload) => {
  state.loading = false;
  state.data = payload;
};

const loadDataFailureAction = ({ state }, error) => {
  state.loading = false;
  state.error = error;
};

const loadDataAction = ({ state, effect }, url) => {
  state.loading = true;
  delete state.error;
  delete state.data;
  effect(fetchEffect, url, loadDataSuccessAction, loadDataFailureAction);
};

const validUrl = "https://api.myjson.com/bins/vrtvf";
const invalidUrl = "https://api.myjson.com/bins/invalid";

const App = () => {
  const [data, error, loading] = useStates("data", "error", "loading");

  function handleClickSuccess() {
    dispatch(loadDataAction, validUrl);
  }

  function handleClickFailure() {
    dispatch(loadDataAction, invalidUrl);
  }

  return (
    <>
      {!loading && (
        <>
          <button onClick={handleClickSuccess}>Load Data Success</button>{" "}
          <button onClick={handleClickFailure}>Load Data Failure</button>
        </>
      )}
      <pre>
        {typeof loading === "boolean" ? (
          loading ? (
            "Loading..."
          ) : error ? (
            <span style={{ color: "red" }}>{error}</span>
          ) : (
            JSON.stringify(data, null, 2)
          )
        ) : (
          ""
        )}
      </pre>
    </>
  );
};

render(<App />, document.getElementById("root"));

Handling action dispatching

Sometimes you want to listen when specified action is dispatched then do something

import { on } from "react-charm";
// module user-management
const SignOutAction = ({ state }) => delete state.accessToken;

// module product
// we should dispose all product state props
on(SignOutAction, ({ state }) => delete state.productList);

Watching state props changes

import { watch } from "react-charm";

watch(
  state => state.counter,
  ({ state }) => {
    console.log("counter changed", state.counter);

    // even you can mutate state
    // watcher will not be called recursively
    state.counter++;
  }
);

setState({
  counter: 1
});

API

setState(nextState:Object)

getState():Object

initState(initialState:Object)

subscribe(subscriber:Function)

on(action:Function, stateMutator:Function):Function

on(actions:Function[], stateMutator:Function):Function

on([[action1:Function, stateMutator1:Function], [action2:Function, stateMutator2:Function], ...]):Function

dispatch(action:Function, ....args:Object[])

useStates(...stateSelector:FunctionOrString[]):Object[]

useActions(...actions:Function[])

withStates(stateMap:Object):Function

withActions(actionMap:Object):Function