3.0.2 • Published 8 years ago
redux-optimistic-manager v3.0.2
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-managerWrap your reducer with
createOptimisticReducerhigher order function, then create a manager for your store, thecreateOptimisticManagerreturnspostActionandrollbackfunction:// store.js import {createStore} from 'redux'; import {createOptimisticManager, createOptimisticReducer} from 'redux-manager'; import reducer from './reducer'; export let store = createStore(createOptimisticReducer(reducer)); export let {postAction, rollback} = createOptimisticManager(store);postAction(action, [transactionId])tells transaction to save a action, iftransactionIdis provided then the action is treated as optimistic,transactionIdcan be any unique value exceptnullandundefined, we recommend using an new object({}) as transaction id. ThepostActionfunction returns whatever you provide asactionargument.rollback(transactionId, [replay = store.dispatch])is to rollback all optimistic actions in certain transaction, you can provide an extrareplayfunction torollback, all saved actions will be dispatch throughreplayfunction.
Create a
transactionIdin your business logic, before you dispatch any action, callpostActionto save it in transaction, you can rollback optimistic ones by callingrollback(transactionId):let newTodo = todo => ({type: 'NEW_TODO', payload: todo}); let notify = message => ({type: 'NOTIFY', payload: message}); let saveTodo = async todo => { // Begin a transaction let transactionId = {}; // Actual action will be saved and re-dispatched on rollback postAction(postAction(notify('Saving todo'))); let newTodoAction = newTodo(todo); // Save and dispatch an optimistic action, this action will be dismissed on rollback dispatch(postAction(newTodo(todo)), transactionId); let createdTodo = await service.post('/todos', todo); // Rollback to dismiss all optimistic actions rollback(transactionId); // Dispatch final actual action, this should also be saved dispatch(postAction(newTodo(createdTodo))); };
Integrate with middleware
redux-optimistic-thunk is an optimistic middleware based on this lib, the code is quite easy to read.
Change Log
2.0.0
- Simplified interfaces, now we need only
postActionandrollbackfunctions. - No longer manage transaction id, you should provide an unique
transactionIdtopostActionandrollbackfunction.
3.0.0
- Refreshed build with single rollup.
- The es module version is now located at
dist/index.mjs. - Add
"sideEffects": falsetopackage.json.