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

redux-status

v0.12.1

Published

A higher-order component decorator for painless state management with Redux and React.

Downloads

36

Readme

redux-status · npm

A higher-order component decorator for painless state management with Redux and React.

Table of Contents

Install

yarn add redux-status
  # or
npm install --save redux-status

Usage

Step 1: Add the redux-status reducer to the Redux store:

import {combineReducers, createStore} from 'redux';
import {reducer as statusReducer} from 'redux-status';

const reducers = combineReducers({
    // 'status' is the default key 'reduxStatus' uses; you can
    // use another key but then you will also need to define
    // the 'getStatusState' option when initializing 'reduxStatus'
    status: statusReducer,
    // other reducers
});

const store = createStore(reducers);

Step 2: Connect components with the reduxStatus decorator:

import React, {PureComponent} from 'react';
import {reduxStatus} from 'redux-status';

@reduxStatus({
    name: 'Counter', // 'name' is required
    initialValues: {
        counter: 0,
    },
})
class Counter extends PureComponent {
    increment = () => {
        this.props.setStatus(prevStatus => ({
            counter: prevStatus.counter + 1,
        }));
    }

    decrement = () => {
        this.props.setStatus(prevStatus => ({
            counter: prevStatus.counter - 1,
        }));
    }

    render() {
        return (
            <div>
                <p>{this.props.status.counter}</p>
                <button onClick={this.increment}>Increment</button>
                <button onClick={this.decrement}>Decrement</button>
            </div>
        );
    }
}

Examples

Example apps can be found under the examples/ directory. They are ported from the official Redux repository, so you can compare both implementations.

API

reduxStatus([options])

A higher-order component decorator that is connected to the Redux store using the connect function from react-redux. It can store plain data as well as handle async jobs with promises (such as data fetching). It uses moize for caching results of promises.

Arguments

  1. [options] (Object): Settings that will be used as defaultProps. Setting options here is optional as React props can be used instead. Defaults to {}. Available properties:
    • [name] (String): A key where the state will be stored under the status reducer. It's an optional property in options, but a required one in general. If it wasn't set here, it must be set with React props.
    • [initialValues] (Object): Values which will be used during initialization, they can have any shape. Defaults to {}.
    • [asyncValues] (Function): A function that takes React props and must return an object. Each key of that object refers to a place in the reducer under which a data will be stored. Each value must be an object with the following properties.
      • promise (Function): A function that takes args as arguments (if specified) and returns a promise. The result of that promise will be memoized and stored in the Redux store.
      • [args] (Array): Arguments that will be passed to the promise function. They must be immutable (booleans, numbers and strings) otherwise the meimozation will not work.
      • [maxAge] (Number): See moize documentation.
      • [maxArgs] (Number): See moize documentation.
      • [maxSize] (Number): See moize documentation.
    • [persist] (Boolean): If false, the state related to that name will be removed when the last component using it unmounts. Defaults to true.
    • [autoRefresh] (Boolean): An option that defines should async functions be called or not, including initial mounting. Setting it to false allows manual refresh handling using the refresh method. Defaults to true.
    • [getStatusState] (Function): A function that takes the entire Redux state and returns the state slice where the reducer was mounted. Defaults to state => state.status.

Returns

A function, that accepts a React component, and returns a higher-order React component.

Passed props

The following props will be passed down to the wrapped component:

  • status (Object): A slice of Redux store.
  • setStatus(nextStatus) (Function): If the nextStatus is a function, it takes a current status as an argument and must return an object that will be shallow merged with the current status. If the nextStatus is an object, it will be shallow merged directly.
  • setStatusTo(statusName, nextStatus) (Function): Similar to setStatus() but also takes in a statusName as the first argument. Recommended for setting data to another statuses.
  • refresh() (Function): Forces the update of async values. Note that it will call the memoized function.
  • initialize(props) (Function): The internal function that is called when the component mounts.
  • destroy() (Function): The internal function that is called when the component unmounts.

The following props are the ones that have been used during the initialization. They are not connected to the store for performance reasons, but it might be changed in the future if there will be a strong reason to do that.

  • statusName (String)
  • persist (Boolean)
  • [getStatusState(state)] (Function)

Instance properties

The following properties are public so they can be called from the outside.

  • status (getter)
  • setStatus(nextStatus)
  • setStatusTo(statusName, nextStatus)
  • refresh()

An example that utilizes instance methods based on the example above:

const Counter = reduxStatus({
    name: 'Counter',
    initialValues: {
        counter: 0,
    },
})(({status}) => <p>{status.counter}</p>);

class CounterController extends PureComponent {
    increment = () => {
        this.counter.setStatus(prevStatus => ({
            counter: prevStatus.counter + 1,
        }));
    }

    decrement = () => {
        this.counter.setStatus(prevStatus => ({
            counter: prevStatus.counter - 1,
        }));
    }

    _getRef = (ref) => {
        this.counter = ref;
    }

    render() {
        return (
            <div>
                <Counter statusRef={this._getRef} />
                <button onClick={this.increment}>Increment</button>
                <button onClick={this.decrement}>Decrement</button>
            </div>
        );
    }
}

Async usage

import React, {PureComponent} from 'react';
import {reduxStatus} from 'redux-status';

@reduxStatus({
    name: 'Async', // 'name' is required
    asyncValues: props => ({ // 'values' is required too
        [props.reddit]: {
            args: [props.reddit],
            promise: reddit => fetch(`https://www.reddit.com/r/${reddit}.json`)
                .then(res => res.json())
                .then(res => res.data.children),
        },
    }),
})
class Async extends PureComponent {
    render() {
        const {status, reddit} = this.props;
        const {pending, refreshing, value} = status[reddit];

        if (!value) {
            return pending ? <h2>Loading...</h2> : <h2>Empty.</h2>;
        }

        return (
            <div style={{opacity: pending || refreshing ? 0.5 : 1}}>
                <ul>
                    {posts.map((post, i) => <li key={i}>{post.data.title}</li>)}
                </ul>
            </div>
        );
    }
}

reducer

A status reducer that should be mounted to the Redux store under the status key.

If you have to mount it to a key other than status, you may provide a getStatusState() function to the reduxStatus() decorator.

Usage

import {combineReducers, createStore} from 'redux';
import {reducer as statusReducer} from 'redux-status';

const reducers = combineReducers({
    status: statusReducer,
    // other reducers
});

const store = createStore(reducers);

selectors

An object with Redux selectors.

getStatusValue(statusName, [getStatusState])

Arguments

  1. statusName (String): The name of the status you are connecting to. Must be the same as the name you gave to reduxStatus().
  2. [getStatusState] (Function): A function that takes the entire Redux state and returns the state slice where the redux-status was mounted. Defaults to state => state.status.

getStatusMeta(statusName, [getStatusState])

Arguments

  1. statusName (String): The name of the status you are connecting to. Must be the same as the name you gave to reduxStatus().
  2. [getStatusState] (Function): A function that takes the entire Redux state and returns the state slice where the redux-status was mounted. Defaults to state => state.status.

actions

An object with all internal action creators. This is an advanced API and most of the time shouldn't be used directly. It is recommended that you use the actions passed down to the wrapped component, as they are already bound to dispatch() and statusName.

initialize(statusName, props)

Arguments

  1. statusName (String)
  2. props (Object): React props.

destroy(statusName)

Arguments

  1. statusName (String)

update(statusName, payload)

Arguments

  1. statusName (String)
  2. payload (Object)

actionTypes

An object with Redux action types.

  • INITIALIZE (String)
  • DESTROY (String)
  • UPDATE (String)
  • prefix (String)

promiseState

A set of functions that are used internally to represent states of async values. These are not intended for public usage.

  • pending(): PromiseStates
  • refreshing(previous?: PromiseState): PromiseState
  • fulfilled(valueOrPromiseState: any): PromiseState
  • rejected(reason: any): PromiseState
  • isPromiseState(maybePromiseState: any): boolean

propTypes

An object with prop types.

  • status (Object)
  • promiseState (Object)