redux-optimist
Optimistically apply actions that can be later commited or reverted.
About this fork
I don't like the memory intensive method that redux-optimist uses, nor do I like the fact that redux-optimistic-ui requires me to wrap my getState.
I thought I'd write something in between.
Installation
npm install redux-optimist
Usage
Step 1: Wrap your top level reducer in redux-optimist
reducers/todos.js
{ }
reducers/status.js
{ }
reducers/index.js
;;;; ;
As long as your top-level reducer returns a plain object, you can use optimist. You don't
have to use Redux.combineReducers
.
optimist
key
Step 2: Mark your optimistic actions with the middleware/api.js
;; let nextTransactionID = 0; { return { if actiontype !== 'ADD_TODO' return ; let transactionID = nextTransactionID++; ; ; }};
Note how we always follow up by either COMMITing the transaction or REVERTing it. If you do neither, you will get a memory leak. Also note that we use a serialisable transactionID such as a number. These should always be unique accross the entire system.
Step 3:
Using this, we can safely fire off ADD_TODO
actions in the knowledge that the UI will update optimisticly, but will revert if the write to the server fails.
App.js
;;; // Note: passing middleware as the last argument to createStore requires redux@>=3.1.0let store = ;console;// {// optimist: {...},// todos: [],// status: {writing: false, error: null}// } store;console;// {// optimist: {...},// todos: ['Use Redux'],// status: {writing: true, error: null}// } // You can apply other actions here and their updates won't get lost// even if the original ADD_TODO action gets reverted. // Some time later...console;// either// {// optimist: {...},// todos: ['Use Redux'],// status: {writing: false, error: null}// }// or// {// optimist: {...},// todos: [],// status: {writing: false, error: Error}// }
License
MIT