0.12.1 • Published 6 years ago

redux-status v0.12.1

Weekly downloads
5
License
MIT
Repository
github
Last release
6 years ago

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)

0.12.1

6 years ago

0.12.0

7 years ago

0.11.0

7 years ago

0.10.2

7 years ago

0.10.1

7 years ago

0.10.0

7 years ago

0.9.0

7 years ago

0.8.0

7 years ago

0.7.6

7 years ago

0.7.5

7 years ago

0.7.4

7 years ago

0.7.3

7 years ago

0.7.2

7 years ago

0.7.1

7 years ago

0.7.0

7 years ago

0.6.0

7 years ago

0.5.3

7 years ago

0.5.2

7 years ago

0.5.1

7 years ago

0.5.0

7 years ago

0.4.0

7 years ago

0.3.0

7 years ago

0.2.1

7 years ago

0.2.0

7 years ago

0.1.0

7 years ago