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
returnspostAction
androllback
function:// store.js;;;let store = ;let postAction rollback = ;postAction(action, [transactionId])
tells transaction to save a action, iftransactionId
is provided then the action is treated as optimistic,transactionId
can be any unique value exceptnull
andundefined
, we recommend using an new object({}
) as transaction id. ThepostAction
function returns whatever you provide asaction
argument.rollback(transactionId, [replay = store.dispatch])
is to rollback all optimistic actions in certain transaction, you can provide an extrareplay
function torollback
, all saved actions will be dispatch throughreplay
function.
-
Create a
transactionId
in your business logic, before you dispatch any action, callpostAction
to save it in transaction, you can rollback optimistic ones by callingrollback(transactionId)
:let type: 'NEW_TODO' payload: todo;let type: 'NOTIFY' payload: message;let saveTodo = async {// Begin a transactionlet transactionId = {};// Actual action will be saved and re-dispatched on rollback;let newTodoAction = ;// Save and dispatch an optimistic action, this action will be dismissed on rollback;let createdTodo = await service;// Rollback to dismiss all optimistic actions;// Dispatch final actual action, this should also be saved;};
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
postAction
androllback
functions. - No longer manage transaction id, you should provide an unique
transactionId
topostAction
androllback
function.
3.0.0
- Refreshed build with single rollup.
- The es module version is now located at
dist/index.mjs
. - Add
"sideEffects": false
topackage.json
.