redux-logic
“One place for all your business logic and action side effects”
Redux middleware that can:
- intercept (validate/transform/augment) actions AND
- perform async processing (fetching, I/O, side effects)
tl;dr
With redux-logic, you have the freedom to write your logic in your favorite JS style:
- plain callback code -
dispatch(resultAction)
- promises -
return axios.get(url).then(...)
- async/await -
result = await fetch(url)
- observables -
ob$.next(action1)
Use the type of code you and your team are comfortable and experienced with.
Leverage powerful declarative features by simply setting properties:
- filtering for action type(s) or with regular expression(s)
- cancellation on receiving action type(s)
- use only response for the latest request
- debouncing
- throttling
- dispatch actions - auto decoration of payloads
Testing your logic is straight forward and simple.
With simple code your logic can:
- intercept actions before they hit the reducer
- validate, verify, auth check actions and allow/reject or modify actions
- transform - augment/enhance/modify actions
- process - async processing and dispatching, orchestration, I/O (ajax, REST, subscriptions, GraphQL, web sockets, …)
Redux-logic makes it easy to use code that is split into bundles, so you can dynamically load logic right along with your split UI.
Server rendering is simplified with redux-logic since it lets you know when all your async fetching is complete without manual tracking.
Inspired by redux-observable epics, redux-saga, and custom redux middleware, redux-logic combines ideas of each into a simple easy to use API.
Quick Example
This is an example of logic which will listen for actions of type FETCH_POLLS and it will perform ajax request to fetch data for which it dispatches the results (or error) on completion. It supports cancellation by allowing anything to send an action of type CANCEL_FETCH_POLLS. It also uses take latest
feature that if additional FETCH_POLLS actions come in before this completes, it will ignore the outdated requests.
The developer can just declare the type filtering, cancellation, and take latest behavior, no code needs to be written for that. That leaves the developer to focus on the real business requirements which are invoked in the process hook.
1 | const fetchPollsLogic = createLogic({ |
Since redux-logic gives you the freedom to use your favorite style of JS code (callbacks, promises, async/await, observables), it supports many features to make that easier, explained in more detail.
Table of contents
- Goals
- Usage
- Full API
- Examples - JSFiddle and full examples
- Comparison summaries to fat action creators, thunks, redux-observable, redux-saga, custom middleware
- SAM/PAL pattern
- Other - todo, inspiration, license
Goals
- organize business logic keeping action creators and reducers clean
- action creators are light and just post action objects
- reducers just focus on updating state
- intercept and perform validations, verifications, authentication
- intercept and transform actions
- perform async processing, orchestration, dispatch actions
- wrap your core business logic code with declarative behavior
- filtered - apply to one or many action types or even all actions
- cancellable - async work can be cancelled
- limiting (like taking only the latest, throttling, and debouncing)
- features to support business logic and large apps
- have access to full state to make decisions
- easily composable to support large applications
- inject dependencies into your logic, so you have everything needed in your logic code
- dynamic loading of logic for splitting bundles in your app
- your core logic code stays focussed and simple, don’t use generators or observables unless you want to.
- create subscriptions - streaming updates
- easy testing - since your code is just a function it’s easy to isolate and test
Usage
1 | npm install rxjs --save |
1 | // in configureStore.js |
processOptions introduced for redux-logic@0.8.2 allowing for even more streamlined code
processOptions
has these new properties which affect the process hook behavior:
dispatchReturn
- the returned value of the process function will be dispatched or if it is a promise or observable then the resolve, reject, or observable values will be dispatched applying any successType or failType logic if defined. Default is determined by arity of process fn,true
if dispatch not provided,false
otherwise. DetailssuccessType
- dispatch this action type using contents of dispatch as the payload (also would work with with promise or observable). You may alternatively provide an action creator function to use instead and it will receive the value as only parameter. Default:undefined
.if successType is a string action type
- create action using successType and provide value as payload. ex: with
successType:'FOO'
, result would be{ type: 'FOO', payload: value }
- create action using successType and provide value as payload. ex: with
if successType is an action creator fn receiving the value as only parameter
- use the return value from the action creator fn for dispatching ex:
successType: x => ({ type: 'FOO', payload: x })
- if the action creator fn returns a falsey value like
undefined
then nothing will be dispatched. This allows your action creator to control whether something is actually dispatched based on the value provided to it.
- use the return value from the action creator fn for dispatching ex:
failType
- dispatch this action type using contents of error as the payload, sets error: true (would also work for rejects of promises or error from observable). You may alternatively provide an action creator function to use instead which will receive the error as the only parameter. Default:undefined
.if failType is a string action type
- create action using failType, provide value as the payload, and set error to true. ex: with
failType:'BAR'
, result would be{ type: 'BAR', payload: errorValue, error: true }
- create action using failType, provide value as the payload, and set error to true. ex: with
if failType is an action creator function receiving the error value as its only parameter
- use the return value from the action creator fn for dispatching. ex:
failType: x => ({ type: 'BAR', payload: x, error: true })
- if the action creator fn returns a falsey value like
undefined
then nothing will be dispatched. This allows your action creator to control whether something is actually dispatched based on teh value provided to it.
- use the return value from the action creator fn for dispatching. ex:
The successType and failType would enable clean code, where you can simply return a promise or observable that resolves to the payload and rejects on error. The resulting code doesn’t have to deal with dispatch and actions directly.
1 | const fetchPollsLogic = createLogic({ |
This is pretty nice leaving us with mainly our business logic code that could be easily extracted and called from here.
Full API
See the docs for the full api
Examples
JSFiddle live examples
- search async axios fetch - live search using debounce and take latest functionality with axios fetch
- search rxjs ajax fetch - live search using debounce and take latest functionality with rxjs ajax fetch
- search rxjs ajax fetch - using processOptions - live search using debounce and take latest with rxjs ajax fetch using processOptions to streamline the code
- async axios fetch - single page - displayed using React
- async rxjs-ajax fetch - async fetching using RxJS ajax which supports XHR abort for cancels
- async axios fetch - single page redux only - just the redux and redux-logic code
- async axios fetch - using processOptions - using processOptions to streamline your code further with React
- async rxjs-ajax fetch - using processOptions - async fetch using RxJS ajax (supporting XHR abort on cancel) and processOptions for clean code.
- async await - react - using ES7 async functions (async/await) displaying with React
- async await - redux only - using ES7 async functions (async/await) - just redux and redux-logic code
- async await - react processOptions - using ES7 async functions (async/await) with processOptions, displayed with React
Full examples
- search-async-fetch - search async fetch example using axios uses debouncing and take latest features
- async-fetch-vanilla - async fetch example using axios
- async-rxjs-ajax-fetch - async fetch example using RxJS ajax (supporting XHR abort on cancel) and redux-actions
- async-fetch-proc-options - async fetch example using axios and the new processOptions feature
- async-rxjs-ajax-proc-options - async RxJS ajax (with XHR abort on cancel) fetch example using axios and the new processOptions feature
- async-await - ES7 async functions - async fetch example using axios and ES7 async functions (async/await)
- async-await - ES7 async functions with processOptions - async fetch example using axios and ES7 async functions (async/await) and using the new processOptions feature
- countdown - a countdown timer implemented with setInterval
- countdown-obs - a countdown timer implemented with Rx.Observable.interval
- form-validation - form validation and async post to server using axios, displays updated user list
- notification - notification message example showing at most N messages for X amount of time, rotating queued messages in as others expire
- search-single-file - search async fetch example with all code in a single file and displayed with React
- single-file-redux - async fetch example with all code in a single file and appended to the container div. Only redux and redux-logic code.
Comparison summaries
Following are just short summaries to compare redux-logic to other approaches.
For a more detailed comparison with examples, see by article in docs, Where do I put my business logic in a React-Redux application?.
Compared to fat action creators
- no easy way to cancel or do limiting like take latest with fat action creators
- action creators would not have access to the full global state so you might have to pass down lots of extra data that isn’t needed for rendering. Every time business logic changes might require new data to be made available
- no global interception using just action creators - applying logic or transformations across all or many actions
- Testing components and fat action creators may require running the code (possibly mocked API calls).
Compared to redux-thunk
- With thunks business logic is spread over action creators
- With thunks there is not an easy way to cancel async work nor to perform (take latest) limiting
- no global interception with thunks - applying logic or transformations across all or many actions
- Testing components and thunked action creators may require running the code (possibly mocked API calls). When you have a thunk (function or promise) you don’t know what it does unless you execute it.
Compared to redux-observable
- redux-logic doesn’t require the developer to use rxjs observables. It uses observables under the covers to provide cancellation, throttling, etc. You simply configure these parameters to get this functionality. You can still use rxjs in your code if you want, but not a requirement.
- redux-logic hooks in before the reducer stack like middleware allowing validation, verification, auth, tranformations. Allow, reject, tranform actions before they hit your reducers to update your state as well as accessing state after reducers have run. redux-observable hooks in after the reducers have updated state so they have no opportuntity to prevent the updates.
Compared to redux-saga
- redux-logic doesn’t require you to code with generators
- redux-saga relies on pulling data (usually in a never ending loop) while redux-logic and logic are reactive, responding to data as it is available
- redux-saga runs after reducers have been run, redux-logic can intercept and allow/reject/modify before reducers run also as well as after
Compared to custom redux middleware
- Both are fully featured to do any type of business logic (validations, tranformations, processing)
- redux-logic already has built-in capabilities for some of the hard stuff like cancellation, limiting, dynamic loading of code. With custom middleware you have to implement all functionality.
- No safety net, if things break it could stop all of your future actions
- Testing requires some mocking or setup
Implementing SAM/PAL Pattern
The SAM (State-Action-Model) pattern is a pattern introduced by Jean-Jacques Dubray. Also known as the PAL (proposer, acceptor, learner) pattern based on Paxos terminology.
A few of the challenging parts of implementing this with a React-Redux application are:
- where to perform the
accept
(interception) of the proposed action performing validation, verification, authentication against the current model state. Based on the current state, it might be appropriate to modify the action, dispatch a different action, or simply suppress the action. - how to trigger actions based on the state after the model has finished updating, referred to as the
NAP
(next-action-predicate).
Custom Redux middleware can be introduced to perform this logic, but you’ll be implementing most everything on your own.
With redux-logic
you can implement the SAM / PAL pattern easily in your React/Redux apps.
Namely you can separate out your business logic from your action creators and reducers keeping them thin. redux-logic provides a nice place to accept, reject, and transform actions before your reducers are run. You have access to the full state to make decisions and you can trigger actions based on the updated state as well.
Solving those SAM challenges previously identified using redux-logic:
- perform acceptance in redux-logic
validate
hooks, you have access to the full state (model) of the app to make decisions. You can perform synchronous or asynchronous logic to determine whether to accept the action and you may augment, modify, substitute actions, or suppress as desired. - Perform NAP processing in redux-logic
process
hooks. The process hook runs after the actions have been sent down to the reducers so you have access to the full model (state) after the updates where you can make decisions and dispatch additional actions based on the updated state.
Inspiration
redux-logic was inspired from these projects:
Minimized/gzipped size with all deps
(redux-logic only includes the modules of RxJS 5 that it uses)
1 | redux-logic.min.js.gz 11KB |
Note: If you are already including RxJS 5 into your project then the resulting delta will be much smaller.
TODO
- add typescript support
- more docs
- more examples
- evaulate additional features as outlined above
Get involved
If you have input or ideas or would like to get involved, you may:
- contact me via twitter @jeffbski - http://twitter.com/jeffbski
- open an issue on github to begin a discussion - https://github.com/jeffbski/redux-logic/issues
- fork the repo and send a pull request (ideally with tests) - https://github.com/jeffbski/redux-logic
- See the contributing guide
Supporters
This project is supported by CodeWinds Training