• Stars
    star
    125
  • Rank 286,335 (Top 6 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 8 years ago
  • Updated about 8 years ago

Reviews

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

Repository Details

Solves challenging redux problems in a clean, understandable, debuggable fasion.

npm version

redux-operations

Solves challenging redux problems in a clean, understandable, debuggable fasion.

##Installation npm i -S redux-operations

What kind of problems can it solve?

Everything you'll ever encounter in the wild:

  • Dynamic state
  • Action watching (eg count how many times a particular action was run)
  • Based on itermediary results (eg 2 reducers sharing the same action & 1 needs the result of the other)
  • Async actions without thunk/promise middleware. Just write your logic directly in your reducer
  • Visual, dare I say graphiQL, API to make debugging a breeze

Where can I see it working?

How's it different from redux-saga?

Risking oversimplification, redux-saga uses generators and puts business logic in the middleware. It also lets you cancel promises.

redux-operations keeps all logic in the reducer by adding info to action.meta.operations behind the scenes. This allows it to solve a few extra hard problems like dynamic state. It also plays nicely with vanilla redux so you only need to use it for the tricky parts of your app. But, if you like a visual API for debugging, you might as well use it for your whole app.

See scalable-frontend-with-elm-or-redux to see how the two solve the same problem and decide which fits your use case.

##Usage

###Create the store enhancer

Just like redux-devtools or applyMiddleware, redux-operations is a storeEnhancer.

API

const storeEnhancer = reduxOperations();

Example

import {createStore} from 'redux'
import {reduxOperations} from 'redux-operations';
return createStore(rootReducer, initialState, reduxOperations());

If you use this in conjunction with redux-devtools, you'll see an enhanced state there:

state = {
  api: <YOUR REDUX-OPERATIONS API HERE>
  userState: <YOUR STATE HERE>
})

There's no need to adjust any of your code, your application only sees what's inside userState.

###Write your reducer

When your store is created, redux-operations ignores your regular reducers and only uses reducers designed for it. These are easily created by using a reducer factory that takes in an operationName, initialState and an object full of "operations". An operation is an action that is specific to the reducer. In other words, one action type has 1 or many operations. This already occurs in the wild, but the execution order is arbitrary and intermediary results are not passed through. The operationName is the same name that you use in your combineReducers. By making you repeat that name here, we allow for perfect compatibility with standard redux.

API

operationReducerFactory(operationName, initialState, reducerObject);

Example

import {operationReducerFactory} from 'redux-operations';
const initialState = 0;
export const counter = operationReducerFactory('counter', initialState, {
  INCREMENT_COUNTER: {
    resolve: (state, action)=> state + 1
  },
  INCREMENT_ASYNC: {
    priority: 1, // if this action type is used in another reducer, this determines which runs first
    resolve: (state, action)=> {
      setTimeout(()=> {
        const {dispatch, locationInState} = action.meta.operations;
        // yes, that counter variable below is a circular reference to the reducer object
        const inc = bindOperationToActionCreators(locationInState, counter, increment);
        dispatch(inc());
      }, 1000);
      return state;
    }
  },
  SET_COUNTER: {
    resolve: (state, action) => action.payload.newValue, // set the state to the variable passed in
    arguments: {
      newValue: {type: Number, description: 'The new value for the counter'} // show this in the API
    }
  }
});

Notice that all the logic occurs in the resolve method, even async actions. In plain redux, this logic is split between the action creator and the resolve function, which subjectively makes the flow harder to follow.

###Integrate into the model-view layer (eg your redux container)

redux-operations works with all frontend frameworks, but we'll show an example of it working in react. For the example, imagine you have 2 counters that share the same reducer. You need to know where in the state tree to find each (called locationInState) and the reducerObject so it can initialize the state at runtime (for dynamically generated states)

First, we need to get the possibly-dynamic state from the state tree.

API

walkState(locationInState, state, reducerObject);

Example

import {counterReducer} from './counterReducer';
import {walkState} from 'redux-operations';

const mapStateToProps = (state, props) => {
  return {
    // `locationInState` is static here, but is usually passed in via props.
    counter: walkState(['counters', 'top'], state, counterReducer);
  }
};

Next, we need to make sure that our action creators attach this info to the new actions. This is done by attaching locationInState and the operationName to the action.meta.operations property. Since the operationName is stored in the reducerObject, we just pass that in. To make it easy, redux-operations offers a HOF to do the work for you. It takes in a single function or an object of functions, similar to redux's bindDispatchToActions.

API

bindOperationtToActionCreators(locationInState, reducerObject, actionCreators);

Example

import {bindOperationToActionCreators} from 'redux-operations';
import {counterReducer} from './counterReducer';
import * from './actionCreators';
import {connect} from 'react-redux';

@connect(mapStateToProps)
export default class Counter extends Component {
 render() {
    const {incrementAsync} = bindOperationToActionCreators(['counters', 'top'], counterReducer, actionCreators);
    return (
      <div>
        <button onClick={() => dispatch(increment())}>+</button>
      </div>
    )
  }
}

More advanced cases

For more advanced use cases, see the Counter example or read the blog post.

More Repositories

1

meatier

🍔 like meteor, but meatier 🍔
JavaScript
3,059
star
2

redux-optimistic-ui

a reducer enhancer to enable type-agnostic optimistic updates
JavaScript
693
star
3

cashay

💰 Relay for the rest of us 💰
JavaScript
453
star
4

trebuchet-client

A friendly siege weapon to get 2-way communication through tough firewalls and bad mobile networks
TypeScript
177
star
5

fast-rtc-swarm

A full-mesh WebRTC swarm built on top of fast-rtc-peer
TypeScript
101
star
6

lolliclock

A material design timepicker based on clockpicker
JavaScript
40
star
7

fast-rtc-peer

a small RTC client for connecting 2 peers
TypeScript
34
star
8

fast-bitset

A fast bitset with some nice methods
JavaScript
34
star
9

cashay-playground

The playground for exploring what's possible with Cashay
JavaScript
33
star
10

EdmondsBlossom

Edmond's maximum weighted matching algorithm (Blossom algorithm) in O(n^3)
JavaScript
30
star
11

redux-socket-cluster

A socket-cluster state snatcher
JavaScript
30
star
12

dataloader-warehouse

A class for sharing dataloaders across GraphQL subscriptions
TypeScript
29
star
13

rich

A decentralized collaborative rich text editor powered by DOM mutations, CRDT, and WebRTC
TypeScript
22
star
14

sanitize-svg

a small script to prevent stored XSS attacks and detect script tags in SVGs
TypeScript
19
star
15

redux-operations-counter-example

An example of solving current redux shortcoming using redux-operations
JavaScript
16
star
16

graphql-trebuchet-client

A graphql client to get your subscriptions through tough firewalls and unreliable mobile networks
TypeScript
14
star
17

react-portal-hoc

A stupid HOC to make a stupid portal so you can make stupid modals
JavaScript
14
star
18

event-source-polyfill

A minimum immplementation of EventSource for IE11 and Edge
TypeScript
13
star
19

react-githubish-mentions

A wrapper for a textarea to offers autocomplete suggestions when triggered by @ or # or whatever
JavaScript
13
star
20

json-deduper

Compress JSON trees by deduplicating nested objects, strings, and numbers
TypeScript
11
star
21

react-hotkey-hoc

mousetrap wrapper for react
JavaScript
10
star
22

dynamic-serializer

crawls a JSON tree replacing dynamic values with a deterministic integer
JavaScript
9
star
23

react-async-hoc

a hoc for async globals
JavaScript
6
star
24

meteor-leaflet-maps

Leaflet, now with lazy loading & namespacing!
JavaScript
6
star
25

relay-linear-publish-queue

Publish changes in the order they're received.
TypeScript
4
star
26

surviveJS-redux

A redux version of the awesome surviveJS tutorial for react & webpack.
JavaScript
3
star
27

hungarian-on3

The hungarian (Kuhn-Munkres) algorithm solved in O(n^3) time
JavaScript
3
star
28

rethinkdb-ts-migrate

Migrations for rethinkdb-ts
TypeScript
3
star
29

meteor-vital-signs

JavaScript
2
star
30

meteorTooltips

Meteor tooltips that turn any template into a tooltip
JavaScript
2
star
31

visage

Signaling + SFU for turnkey WRTC (WIP)
TypeScript
2
star
32

event-target-polyfill

EventTarget polyfill for IE11 and Edge from https://developer.mozilla.org/en-US/docs/Web/API/EventTarget#Example
TypeScript
2
star
33

hepha

Aphrodite for global styles
JavaScript
1
star
34

performant-material-input

A feature-rich material design input box with hardware acceleration
CSS
1
star
35

todo-modern-subs

JavaScript
1
star