Package Exports
- redux-optimistic-manager
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (redux-optimistic-manager) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
redux-optimistic-manager
redux-optimistic-manager is a lib aimed to simplify optimistic UI implement in redux environment. this lib uses a transaction based method to handle actual and optimistic actions, rolling back optimistic ones in a future point.
How to use
Using redux-optimistic-manager is simple.
Install it:
npm install --save redux-optimistic-manager
Wrap your reducer with
createOptimisticReducer
higher order function, then create a manager for your store, thecreateOptimisticManager
returns atransaction
function:// store.js import {createStore} from 'redux'; import {createOptimisticManager, createOptimisticReducer} from 'redux-manager'; import reducer from './reducer'; export let store = createStore(createOptimisticReducer(reducer)); export let transaction = createOptimisticManager(store);
Begin a transaction before your business logic, a transaction simply gives you 4 functions:
import {transaction} from './store'; let {postAction, postOptimisticAction, postExternalAction, rollback} = transaction();
postAction(action)
tells transaction to save a simple action.postOptimisticAction(action)
tells transaction to save a optimistic action which should be dismissed back when this transaction rolls back.postExternalAction(action)
is to save an action which does not belong to this transaction, this is designed for 3rd-party middlewares.rollback()
is to rollback all optimistic actions in this transaction.
Before you dispatch any action, call
postAction
orpostOptimisticAction
to save it in transaction, you can rollback optimistic ones by callingrollback()
:let newTodo = todo => ({type: 'NEW_TODO', payload: todo}); let notify = message => ({type: 'NOTIFY', payload: message}); let saveTodo = async todo => { // Begin a transaction let {postAction, postOptimisticAction, rollback} = transaction(); // Actual action will be saved and re-dispatched on rollback let notifyAction = notify('Saving todo'); postAction(notify); dispatch(notify); let newTodoAction = newTodo(todo); // Save and dispatch an optimistic action, this action will be dismissed on rollback postOptimisticAction(newTodoAction); dispatch(newTodoAction); let createdTodo = await service.post('/todos', todo); // Rollback to dismiss all optimistic actions rollback(); // Dispatch final actual action, this should also be saved let finalAction = newTodo(createdTodo0; postAction(finalAction); dispatch(finalAction); };
Integrate with middleware
redux-optimistic-thunk is an optimistic middleware based on this lib, the code is quite easy to read.