1.1.1 • Published 5 years ago
react-statecraft v1.1.1
React Statecraft
Pure State Mutation & Event Driven Side Effects
You may like this library if:
- You like state changes to be the result of pure functions
- You dislike updating 37 files to make a simple state change
- You want to update state from a promise resolution without extra steps/libraries
- You want to handle side effects through events subscribed to state changes
Install
$ npm i -S react-statecraft
Usage
import React from 'react'
import StateContainer from 'react-statecraft'
// Setup
const state = { title: 'Initial Title' }
const GlobalContainer = new StateContainer(state, { debug: true })
const { action, effect, Provider, Consumer } = GlobalContainer
// Actions
const setTitleAction = title => ({ title })
const setTitle = action(setTitleAction, ['SAVE_STATE'])
// Effects
effect('SAVE_STATE', state => {
localStorage.setItem('stored-state', state)
})
const handleClick = () => setTitle(prompt('Set new title'))
export const App = () => (
<Provider>
<Consumer>
{({ title }) => (
<>
<h1>{title}</h1>
<button onClick={handleClick}>Set Title</button>
</>
)}
</Consumer>
</Provider>
)
Example Codesandbox
API
Class
StateContainer(initialState[, options])
initialState
: object for initial stateoptions
: (optional){ debug: Boolean }
- Returns: a class instance for managing all child state.
Class Components
StateContainer.Consumer(getProps)
getProps
: function that takes state and returns an object used as props in the render functionchildren
: uses a render function to pass state to children
StateContainer.Provider
- The
Provider
from React's context API
Class Methods
StateContainer.action(actionFn[, effects])
actionFn
: a function that eventually returns new state. Ifnull
is returned, the state change will abort. Valid return values are:- object representing state changes
- a Promise that resolves to an object representing state changes
- a function that takes current state and returns one of the above
effects
: (optional) an array of registered effect names that will run sequentially once the state change is complete- Returns: a function that acts like
actionFn
but effects state change. It returns the value thatactionFn
returns.
StateContainer.connect(component[, props])
component
: a React componentprops
: a function that takes state and returns an object used as props for the wrapped component.- Returns: a component that receives state from the
StateContainers
context.
StateContainer.effect(name, effectFn)
name
: string that references the registered effecteffectFn
: function that takes(state, prevState)
to use in side effects- Returns:
undefined
StateContainer.getState()
- Returns: current state object
Class Properties
StateContainer.context
- The React context object
StateContainer.effects
- The registered effects
StateContainer.mutations
- List of mutations since app load
StateContainer.options
- The options passed to the class constructor