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

riddl-js

v1.0.4

Published

Lightweight ReactJS state management library

Downloads

1

Readme

Riddl.js (Little Redux)

Lightweight ReactJS state-management API using React.Context.

Author: bbgrabbag


Description

Riddl.js is a ReactJS mini-library for intuitively managing global state. It consists of four very simple parts: globalState, setGlobalState, connect and Provider.

  • globalState is an object representing the state of your application.
  • setGlobalState is the declarative function for defining new states.
  • connect is a HoC which lets individual components communicate with the global state
  • Provider is a wrapper component which houses the single source of truth (the global state) for your application;

Install

npm install --save riddl-js

Getting Started

Riddl.js aims to make managing the state of an app as intuitive as that of a local component. Simply define your global state and inject it directly into your App:

// import the Provider component
import {Provider} from "riddl-js";

// define your global state
const globalState = {
    loggedIn: false
}

// pass it to the provider via props
render(
    <Provider globalState = {globalState}>
        <App />
    </Provider>
    , document.getElementById("root"));

The connect function simply provides the globalState object and setGlobalState function to any component via props automatically:

import {connect} from "riddl-js";

//The entire global state is available via props
const HomeScreen = props => (
    <div>{props.loggedIn ? "Welcome Riddl user!" : "You are not logged in"}</div>
);

export connect(HomeScreen);
import {connect} from "riddl-js";

//Declaratively change state using `setGlobalState`
const Auth = props => (
    <button onClick={() => props.setGlobalState({loggedIn: true})}>Login</button>
);

export connect(Auth);

setGlobalState is really just setState

setGlobalState is really just the built-in React component method setState bound to the <Provider>. That means it works the exact same way in which you're already familiar. For example, if you need to access the previous state:

props.setGlobalState(prevState => ({foo: prevState.foo + "bar"}));

Same thing for callbacks:

props.setGlobalState({foo: "bar"}, () => props.setGlobalState({foo : "BAR"})));

Asynchronous State Changes / Rendering

One of the core principles of Flux and Redux is that state changes should be predictable and consistent. Promises make this especially challenging.

Fortunately, since Riddl exposes the actual setGlobalState function to the scope of a connected component, making predictable state changes is trivial:

componentDidMount(){
    this.props.setGlobalState({loading: true});
    fetch('/data')
    .then(response => return response.json())
    .then(data => this.props.setGlobalState({data, loading: false}))
    .catch(err => this.props.setGlobalState({err, loading: false}))
}

The connect function

Riddl's connect function is inspired from react-redux. However it has been slightly condensed. By default the entire globalState is provided via props. mapStateToProps is an optional second parameter, which lets you extract a specific portion of the global state you need:

//globalState --> {portion: {foo: "bar"}, rest: {}}

const NeedsPartOfState = props => (
    <div>
        {props.foo}
    </div>
)

export default connect(NeedsPartOfState, state => state.portion);

The third parameter (also optional) is a special object reserved for what are called transmitters.

    //...
    export default connect(MyComponent, null, {
        transmitter1, 
        transmitter2, 
        transmitter3
        });

Riddl transmitters are simply functions that return callbacks with setGlobalState as a parameter. They are based on the redux-thunk design of using dispatch within asynchronous action creators:

// transmitters.js
export const coinflip = guess => setGlobalState => (
        new Promise((res, rej)=>{
        setGlobalState({result: "Flipping!!"});
        let result = Math.random() < .5 ? "HEADS" : "TAILS";
        setTimeout(()=> result === guess ? res("YOU WON!") : rej("YOU LOST!"), 1200);
    })
    .then(victory => setGlobalState({result:victory}))
    .catch(defeat => setGlobalState({result:defeat}))
)
import {coinFlip} from "transmitters.js";

const Game = props => (
    <div>
        <button onClick={()=>props.coinflip("HEADS")}>Click to flip</button>
    </div>
);
export default connect(Game, null, {coinflip});
const Score = props => (
    <div>{props.result}</div>
);

export default connect(Score);

Notice in the example that the transmitter coinflip is called from props. This is because the connect function is responsible for providing transmitters setGlobalState before they are attached to props.

Organization

It is easiest to store your transmitters in a separate file and export them as needed. By design Riddl doesn't require a strict folder structure, but here is a simple example:

/src
    /components
    App.js
    index.js
    /transmitters
        index.js

If you are finding yourself with lots of transmitters and a large state, consider breaking them up into separate files:

// /transmitters/auth.js

 export const login = credentials => setGlobalState => {
     //...
 }
 export const logout = () => setGlobalState => {
     //...
 }

 export default {
     isAuthenticated: false,
     user: null
 }
// /src/index.js
import auth from "./transmitters/auth.js";
import data from "./transmitters/data.js";

const globalState = {auth, data};

render(
    <Provider globalState={globalState} >
        <App />
    </Provider>,
    document.getElementById("root");
    )

API Reference

§ <Provider>

Wrapper component for the application. Houses the Context.Provider and globalState.

Props

Name | Type | Default Value | Description --- | --- | --- | --- globalState [required] | Object | N/A | The initial state of the application

import {Provider} from "riddl-js";

render(
    <Provider globalState={{key: "value"}}> 
        <App /> 
    </Provider>
    )

§ connect

Utility function for linking the Provider to other components in the React component tree.

Args

Name | Type | Default Value | Description --- | --- | --- | --- Component [required] | React Component | N/A | The React component to be given globalState and setGlobalState via props mapStateToProps [optional] | Function | state => state | Callback function for importing parts of state into the component transmitters [optional] | Object | {} | Useful for connecting asynchronous functions to a component via props

import {connect} from "riddl-js";

const transmitter = ()=> setGlobalState => http(url).then(data => setGlobalState({data}));

const MyComponent = props => (
    <div>
        <button onClick={props.transmitter}>GET</button>
    </div>
)

connect(MyComponent, null, {transmitter});