• Stars
    star
    592
  • Rank 75,570 (Top 2 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 7 years ago
  • Updated about 1 month ago

Reviews

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

Repository Details

Automate the Redux boilerplate.

Autodux

Coverage Status

Redux on autopilot.

Brought to you by EricElliottJS.com and DevAnywhere.io.

Install

npm install --save autodux

And then in your file:

import autodux from 'autodux';

Or using CommonJS syntax:

const autodux = require('autodux');

Redux on Autopilot

Autodux lets you create reducers like this:

export const {
  actions: {
    setUser, setUserName, setAvatar
  },
  selectors: {
    getUser, getUserName, getAvatar
  }
} = autodux({
  slice: 'user',
  initial: {
    userName: 'Anonymous',
    avatar: 'anon.png'
  }
});

That creates a full set of action creators, selectors, reducers, and action type constants -- everything you need for fully functional Redux state management.

Everything's on autopilot -- but you can override everything when you need to.

Why

Redux is great, but you have to make a lot of boilerplate:

  • Action type constants
  • Action creators
  • Reducers
  • Selectors

It's great that Redux is such a low-level tool. It's allowed a lot of flexibility and enabled the community to experiment with best practices and patterns.

It's terrible that Redux is such a low-level tool. It turns out that:

  • Most reducers spend most of their logic switching over action types.
  • Most of the actual state updates could be replaced with generic tools like "concat payload to an array", "remove object from array by some prop", or "increment a number". Better to reuse utilities than to implement these things from scratch every time.
  • Lots of action creators don't need arguments or payloads -- just action types.
  • Action types can be automatically generated by combining the name of the state slice with the name of the action, e.g., counter/increment.
  • Lots of selectors just need to grab the state slice.

Lots of Redux beginners separate all these things into separate files, meaning you have to open and import a whole bunch of files just to get some simple state management in your app.

What if you could write some simple, declarative code that would automatically create your:

  • Action type constants
  • Reducer switching logic
  • State slice selectors
  • Action object shape - automatically inserting the correct action type so all you have to worry about is the payload
  • Action creators if the input is the payload or no payload is required, i.e., x => ({ type: 'foo', payload: x })
  • Action reducers if the state can be assigned from the action payload (i.e., {...state, ...payload})

Turns out, when you add this simple logic on top of Redux, you can do a lot more with a lot less code.

import autodux, { id } from 'autodux';

export const {
  reducer,
  initial,
  slice,
  actions: {
    increment,
    decrement,
    multiply
  },
  selectors: {
    getValue
  }
} = autodux({
  // the slice of state your reducer controls
  slice: 'counter',

  // The initial value of your reducer state
  initial: 0,

  // No need to implement switching logic -- it's
  // done for you.
  actions: {
    increment: state => state + 1,
    decrement: state => state - 1,
    multiply: (state, payload) => state * payload
  },

  // No need to select the state slice -- it's done for you.
  selectors: {
    getValue: id
  }
});

As you can see, you can destructure and export the return value directly where you call autodux() to reduce boilerplate to a minimum. It returns an object that looks like this:

{
  initial: 0,
  actions: {
    increment: { [Function]
      type: 'counter/increment'
    },
    decrement: { [Function]
      type: 'counter/decrement'
    },
    multiply: { [Function]
      type: 'counter/multiply'
    }
  },
  selectors: {
    getValue: [Function: wrapper]
  },
  reducer: [Function: reducer],
  slice: 'counter'
}

Let's explore that object a bit:

const actions = [
  increment(),
  increment(),
  increment(),
  decrement()
];

const state = actions.reduce(reducer, initial);

console.log(getValue({ counter: state })); // 2
console.log(increment.type); // 'counter/increment'

API Differences

Action creators, reducers and selectors have simplified APIs.

Automate (Almost) Everything with Defaults

With autodux, you can omit (almost) everything.

Default Actions

An action is an action creator/reducer pair. Usually, these line up in neat 1:1 mappings. It turns out, you can do a lot with some simple defaults:

  • A set${slice} action lets you set any key in your reducer -- basically: {...state, ...payload}. If your slice is called user, the set creator will be called setUser.
  • Actions for set{key} will exist for each key in your initial state. If you have a key called userName, you'll have an action called setUserName created automatically.

Default Selectors

Like action creators and reducers, selectors are automatically created for each key in your initial state. get{key} will exist for each key in your initial state., and get{slice} will exist for the entire reducer state.

For simple reducers, all the action creators, reducers, and selectors can be created for you automatically. All you have to do is specify the initial state shape and export the bindings.

Action Creators

Action creators are optional! If you need to set a username, you might normally create an action creator like this:

const setUserName = userName => ({
  type: 'userReducer/setUserName',
  payload: userName
})

With autodux, if your action creator maps directly from input to payload, you can omit it. autodux will do it for you.

By omitting the action creator, you can shorten this:

actions: {
  multiply: {
    create: by => by,
    reducer: (state, payload) => state * payload
  }
}

To this:

actions: {
  multiply: (state, payload) => state * payload
}

No need to set the type

You don't need to worry about setting the type in autodux action creators. That's handled for you automatically. In other words, all an action creator has to do is return the payload.

With Redux alone you might write:

const setUserName = userName => ({
  type: 'userReducer/setUserName',
  payload: userName
})

With autodux, that becomes:

userName => userName

Since that's the default behavior, you can omit that one entirely.

You don't need to create action creators unless you need to map the inputs to a different payload output. For example, if you need to translate between an auth provider user and your own application user objects, you could use an action creator like this:

({ userId, displayName }) => ({ uid: userId, userName: displayName })

Here's how you'd implement our multiply action if you want to use a named parameter for the multiplication factor:

//...
actions: {
  multiply: {
    // Destructure the named parameter, and return it
    // as the action payload:
    create: ({ by }) => by,
    reducer: (state, payload) => state * payload
  }
}
//...

Reducers

Note: Reducers are optional. If your reducer would just assign the payload props to the state ({...state, ...payload}), you're already done.

No switch required

Switching over different action types is automatic, so we don't need an action object that isolates the action type and payload. Instead, we pass the action payload directly, e.g:

With Redux:

const INCREMENT = 'INCREMENT';
const DECREMENT = 'DECREMENT';
const MULTIPLY = 'MULTIPLY';

const counter = (state = 0, action = {}) {
  switch (action.type){
    case INCREMENT: return state + 1;
    case DECREMENT: return state - 1;
    case MULTIPLY : return state * action.payload
    default: return state;
  }
};

With Autodux, action type handlers are switched over automatically. No more switching logic or manual juggling with action type constants.

const counter = autodux({
  slice: 'counter',
  initial: 0,
  actions: {
    increment: state => state + 1,
    decrement: state => state - 1,
    multiply: (state, payload) => state * payload
  }
});

Autodux infers action types for you automatically using the slice and the action name, and eliminates the need to write switching logic or worry about (or forget) the default case.

Because the switching is handled automatically, your reducers don't need to worry about the action type. Instead, they're passed the payload directly.

Selectors

Note: Selectors are optional. By default, every key in your initial state will have its own selector, prepended with get and camelCased. For example, if you have a key called userName, a getUserName selector will be created automatically.

Selectors are designed to take the application's complete root state object, but the slice you care about is automatically selected for you, so you can write your selectors as if you're only dealing with the local reducer.

This has some implications with unit tests. The following selector will just return the local reducer state (Note: You'll automatically get a default selector that does the same thing, so you don't ever need to do this yourself):

import { autodux, id } from 'autodux';

const counter = autodux({
  // stuff here
  selectors: {
    getValue: id // state => state
  },
  // other stuff

In your unit tests, you'll need to pass the key for the state slice to mock the global store state:

test('counter.getValue', assert => {
  const msg = 'should return the current count';
  const { getValue } = counter.selectors;

  const actual = getValue({ counter: 3 });
  const expected = 3;

  assert.same(actual, expected, msg);
  assert.end();
});

Although you should avoid selecting state from outside the slice you care about, the root state object is passed as a convenience second argument to selectors:

import autodux from 'autodux';

const counter = autodux({
  // stuff here
  selectors: {
    // other selectors
    rootState: (_, root) => root
  },
  // other stuff

In your unit tests, this allows you to retrieve the entire root state:

test('counter.rootState', assert => {
  const msg = 'should return the root state';
  const { rootState } = counter.selectors;

  const actual = rootState({ counter: 3, otherSlice: 'data' });
  const expected = { counter: 3, otherSlice: 'data' };

  assert.same(actual, expected, msg);
  assert.end();
});

Extras

assign = (key: String) => reducer: Function

Often, we want our reducers to simply set a key in the state to the payload value. assign() makes that easy. e.g.:

const {
  actions: {
    setUserName,
    setAvatar
  },
  reducer
} = autodux({
  slice: 'user',
  initial: {
    userName: 'Anonymous',
    avatar: 'anonymous.png'
  },
  actions: {
    setUserName: assign('userName'),
    setAvatar: assign('avatar')
  }
});

const userName = 'Foo';
const avatar = 'foo.png';

const state = [
  setUserName(userName),
  setAvatar(avatar)
].reduce(reducer, undefined);
// => { userName: 'Foo', avatar: 'foo.png' }

Since that's the default behavior when actions are omitted, you can also shorten that to:

const {
  actions: {
    setUserName,
    setAvatar
  },
  reducer
} = autodux({
  slice: 'user',
  initial: {
    userName: 'Anonymous',
    avatar: 'anonymous.png'
  }
});

id = x => x

Useful for selectors that simply return the slice state:

selectors: {
  getValue: id
}

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

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
4

moneysafe

Convenient, safe money calculations in JS
JavaScript
452
star
5

credential

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

rfx

Self documenting runtime interfaces.
JavaScript
277
star
7

redux-dsm

Declarative state machines for Redux: Reduce your async-state boilerplate.
JavaScript
222
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
168
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

saas-questions

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

applitude

JavaScript application namespacing and module management.
JavaScript
8
star
39

grange

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

talks-and-interviews

A list of my talks and interviews.
7
star
41

tinyerror

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

jQuery.outerHTML

A tiny outerHTML shim for jQuery
JavaScript
6
star
43

connect-cache-control

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

nfdata

NFData - A metadata proposal for NFT interoperability
5
star
45

xforms

xforms
JavaScript
5
star
46

sparkly

Ignite Learning, Inspire Creation
CSS
5
star
47

clctr

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

ofilter

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

rejection

You gotta lose to win.
JavaScript
3
star
50

colab

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

slides-intro-to-js-objects

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

slides-modular-javascript

Modular JavaScript With npm and Node Modules
CoffeeScript
2
star
53

testling-jasmine

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

hifi

Flow based programming for Node services.
1
star
55

resource-acl

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

pja-guestlist-client

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

course-primer

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

mapall

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

pja-sections

Draft sections for "Programming JavaScript Applications"
1
star
60

maybe-assign

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