redux-status
v0.12.1
Published
A higher-order component decorator for painless state management with Redux and React.
Downloads
36
Maintainers
Readme
redux-status ·
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
[options]
(Object): Settings that will be used asdefaultProps
. Settingoptions
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 thestatus
reducer. It's an optional property inoptions
, 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 Reactprops
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 takesargs
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 thepromise
function. They must be immutable (booleans, numbers and strings) otherwise the meimozation will not work.[maxAge]
(Number): Seemoize
documentation.[maxArgs]
(Number): Seemoize
documentation.[maxSize]
(Number): Seemoize
documentation.
[persist]
(Boolean): Iffalse
, the state related to thatname
will be removed when the last component using it unmounts. Defaults totrue
.[autoRefresh]
(Boolean): An option that defines should async functions be called or not, including initial mounting. Setting it tofalse
allows manual refresh handling using therefresh
method. Defaults totrue
.[getStatusState]
(Function): A function that takes the entire Redux state and returns the state slice where thereducer
was mounted. Defaults tostate => 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 thenextStatus
is a function, it takes a current status as an argument and must return an object that will be shallow merged with the currentstatus
. If thenextStatus
is an object, it will be shallow merged directly.setStatusTo(statusName, nextStatus)
(Function): Similar tosetStatus()
but also takes in astatusName
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
statusName
(String): The name of the status you are connecting to. Must be the same as thename
you gave toreduxStatus()
.[getStatusState]
(Function): A function that takes the entire Redux state and returns the state slice where theredux-status
was mounted. Defaults tostate => state.status
.
getStatusMeta(statusName, [getStatusState])
Arguments
statusName
(String): The name of the status you are connecting to. Must be the same as thename
you gave toreduxStatus()
.[getStatusState]
(Function): A function that takes the entire Redux state and returns the state slice where theredux-status
was mounted. Defaults tostate => 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
statusName
(String)props
(Object): React props.
destroy(statusName)
Arguments
statusName
(String)
update(statusName, payload)
Arguments
statusName
(String)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)