• Stars
    star
    222
  • Rank 178,525 (Top 4 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created about 8 years ago
  • Updated 11 days ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Declarative state machines for Redux: Reduce your async-state boilerplate.

Redux DSM

Declarative State Machines for Redux: Reduce your async-state boilerplate.

Redux-dsm takes a nested array of transitions and states and automatically generates:

  • Reducers to manage all state transitions, complete with logic that will not let your app get into an invalid state (according to the graph you supply)
  • Action creators and action types to trigger all transitions

Status

In production use on DevAnywhere.io.

Install

npm install --save redux-dsm

And then in your file :

import dsm from 'redux-dsm';

Or using CommonJS modules :

var dsm = require('redux-dsm');

Why?

Your state isn't always available synchronously all the time. Some state has to be loaded asynchronously, which requires you to cycle through UI states representing concepts like fetching, processing, error, success, and idle states. In fact, a simple ajax fetch might have up to 7 transitions leading into 4 different states:

Transition        Next Status
['initial',           'idle']
['fetch',         'fetching']
['cancel',            'idle']
['report error',     'error']
['handle error',      'idle']
['report success', 'success']
['handle success',    'idle']

Your view code will look at the status and payload to determine whether or not to render spinners, success messages, error messages, empty states, or data. I don't know about you, but I sometimes forget some of those transitions or states.

Every app I've ever written needs to do this a bunch of times. Since I switched to Redux, I handle all of my view state transitions by dispatching action objects, and that requires writing a bunch of boilerplate, such as action types (e.g., myComponent::FETCH_FOO::FETCH), and action creators (which your view or service layers can call to create actions without forcing you to import all those action type constants everywhere).

This little library takes a few declarative inputs and spits out all of the boilerplate for you, including a mini reducer that you can combine with your feature-level reducers.

Can I Use it With x?

This library is not just for ajax, though that will be a very common use-case, and it doesn't care how you handle your async I/O. You can use it with Sagas, redux-thunks, action creators with side-effects, etc..., or just use it by itself and manually wire up your async I/O.

You don't even have to use it with Redux -- anything that uses reducer-based state is fine, including ngrx/store or even Array.prototype.reduce().

Usage Example

import dsm from 'redux-dsm';

// ['action', 'next state',
//   ['scoped action', 'another state']
// ]
// e.g., in the following example, from 'fetching' state, we can:
// * cancel
// * report an error
// * report success
const fetchingStates = ['initial', 'idle',
  ['fetch', 'fetching',
    ['cancel', 'idle'],
    ['report error', 'error',
      ['handle error', 'idle']
    ],
    ['report success', 'success',
      ['handle success', 'idle']
    ]
  ]
];

// ({
//   component?: String,
//   description?: String,
//   actionStates: Array,
//   delimiter?: String
// }) => { actions: Object, actionCreators: Object, reducer: Function }
const foo = dsm({
  component: 'myComponent',
  description: 'fetch foo',
  actionStates: fetchingStates
});

.actions: Object

actions is an object with camelCased keys and strings corresponding to your state transitions. If you use the returned .actionCreators, you probably don't need to use these, but it's handy for debugging. For the above example, it returns:

  "actions": {
    "fetch": "myComponent::FETCH_FOO::FETCH",
    "cancel": "myComponent::FETCH_FOO::CANCEL",
    "reportError": "myComponent::FETCH_FOO::REPORT_ERROR",
    "handleError": "myComponent::FETCH_FOO::HANDLE_ERROR",
    "reportSuccess": "myComponent::FETCH_FOO::REPORT_SUCCESS",
    "handleSuccess": "myComponent::FETCH_FOO::HANDLE_SUCCESS"
  }

.actionCreators: Object

actionCreators will be an object with camelCased keys and function values corresponding to your state transitions. For each transition, an action creator is created which will automatically fill in the correct action type, and pass through payload to the state.

The example fetch state machine will produce the following actionCreators:

fetch()
cancel()
reportError()
handleError()
reportSuccess()
handleSuccess()

.reducer: (state, action) => state

.reducer() is a normal Redux reducer function that takes the current state and an action object, and returns the new state. Matching action objects can be created using the .actionCreators. The reducer can be combined with a parent reducer using combineReducers(). Any payload passed into an action creator will be passed through to state.payload.

State: { status: String, payload: Any }

The state object will have two keys, status and payload. In the example above, status will be one of idle, fetching, error, or success.

By default, the payload key is an object with type: 'empty'.

More Repositories

1

rtype

Intuitive structural type notation for JavaScript.
JavaScript
1,129
star
2

react-pure-component-starter

A pure component dev starter kit for React.
JavaScript
792
star
3

autodux

Automate the Redux boilerplate.
JavaScript
592
star
4

h5Validate

An HTML5 form validation plugin for jQuery. Works on all major browsers, both new and old. Implements inline, realtime validation best practices (based on surveys and usability studies). Developed for production use in e-commerce. Currently in production with millions of users.
JavaScript
577
star
5

moneysafe

Convenient, safe money calculations in JS
JavaScript
452
star
6

credential

Easy password hashing and verification in Node. Protects against brute force, rainbow tables, and timing attacks.
JavaScript
348
star
7

rfx

Self documenting runtime interfaces.
JavaScript
277
star
8

speculation

JavaScript promises are made to be broken. Speculations are cancellable promises.
JavaScript
197
star
9

irecord

An immutable store that exposes an RxJS observable. Great for React.
JavaScript
192
star
10

the-software-developers-library

The Software Developer's Library: a treasure trove of books for people who love code. Curated by Eric Elliott
192
star
11

react-things

A exploratory list of React ecosystem solutions
174
star
12

express-error-handler

A graceful error handler for Express and Restify applications.
JavaScript
169
star
13

feature-toggle

A painless feature toggle system in JavaScript. Decouple development and deployment.
JavaScript
155
star
14

ogen

Write synchronous looking code & mix synchronous & asynchronous results using generators & observables.
JavaScript
129
star
15

tdd-es6-react

Examples of TDD in ES6 with React
95
star
16

react-hello

A hello world example React app
JavaScript
63
star
17

fluentjs1

Talk - Fluent JavaScript Part 1: Prototypal OO. Learn to code like a JS native. Take advantage of JavaScript's distinguishing features in order to write better code.
JavaScript
53
star
18

neurolib

Neuron emulation tools
JavaScript
52
star
19

the-two-pillars-of-javascript-talk

References from "The Two Pillars of JavaScript" talk
51
star
20

maybearray

Native JavaScript Maybes built with arrays.
JavaScript
49
star
21

qconf

Painless configuration with defaults file, environment variables, arguments, function parameters.
JavaScript
45
star
22

object-list

Treat arrays of objects like a db you can query.
JavaScript
43
star
23

gql-validate

Validate a JS object against a GraphQL schema
JavaScript
33
star
24

bunyan-request-logger

Automated request logging middleware for Express. Powered by Bunyan.
JavaScript
29
star
25

tinyapp

A minimal, modular, client-side application framework.
JavaScript
28
star
26

arraygen

Turn any array into a generator.
JavaScript
28
star
27

dpath

Dot Path - FP sugar for immutables
JavaScript
22
star
28

rootrequire

npm install --save rootrequire # then `var root = require('rootrequire'), myLib = require(root + '/path/to/lib.js');`
JavaScript
19
star
29

siren-resource

Resourceful routing with siren+json hypermedia for Express.
JavaScript
18
star
30

version-healthcheck

A plug-and-play /version route for the Node.js Express framework.
JavaScript
17
star
31

react-easy-universal

Universal Routing & Rendering with React & Redux was too hard. Now it's easy.
JavaScript
16
star
32

odotjs

A prototypal OO library for JavaScript
JavaScript
13
star
33

todotasks

TodoMVC for task runners. Not sure which task runner to use? Take a look at some reference implementations.
JavaScript
12
star
34

react-test-demo

React Test Demo
CSS
12
star
35

react-faves

Favorite React Tools
12
star
36

jiron

Make your API self documenting and your clients adaptable to API changes.
11
star
37

JSbooks

Directory of free Javascript ebooks
CSS
11
star
38

saas-questions

SaaS Questions: The most important questions every SaaS company should have answers to.
10
star
39

applitude

JavaScript application namespacing and module management.
JavaScript
8
star
40

grange

Generate all sorts of values based on a range of numbers.
JavaScript
7
star
41

talks-and-interviews

A list of my talks and interviews.
7
star
42

tinyerror

Easy custom errors in browsers, Node, and Applitude
JavaScript
7
star
43

jQuery.outerHTML

A tiny outerHTML shim for jQuery
JavaScript
6
star
44

connect-cache-control

Connect middleware to prevent the browser from caching the response.
JavaScript
6
star
45

nfdata

NFData - A metadata proposal for NFT interoperability
5
star
46

xforms

xforms
JavaScript
5
star
47

sparkly

Ignite Learning, Inspire Creation
CSS
5
star
48

clctr

Event emitting collections with iterators (like Backbone.Collection).
JavaScript
3
star
49

ofilter

Array.prototype.filter for objects.
JavaScript
3
star
50

rejection

You gotta lose to win.
JavaScript
3
star
51

colab

A project collaboration platform centered on live video streaming and monetization.
CSS
3
star
52

slides-intro-to-js-objects

A basic (and short) overview of objects in JavaScript.
JavaScript
2
star
53

slides-modular-javascript

Modular JavaScript With npm and Node Modules
CoffeeScript
2
star
54

testling-jasmine

run jasmine tests in all the browsers with testling
JavaScript
2
star
55

hifi

Flow based programming for Node services.
1
star
56

resource-acl

An ACL intended for use with express-resource.
1
star
57

pja-guestlist-client

The browser client for Guestlist. A demo app for Programming JavaScript Applications.
JavaScript
1
star
58

course-primer

A primer for the "Learn JavaScript with Eric Elliott" course series. Prerequisite for all courses.
1
star
59

mapall

Given an array of promises, map to a same-ordered array of resolutions or rejections.
1
star
60

pja-sections

Draft sections for "Programming JavaScript Applications"
1
star
61

maybe-assign

Like Object.assign, but skip null or undefined props.
1
star