Optimistically apply actions that can be later commited or reverted.
Optimistically apply actions that can be later commited or reverted.
Optimistically apply actions that can be later commited or reverted.
npm install redux-optimistreducers/todos.jsexport default function todos(state = [], action) {
switch (action.type) {
case 'ADD_TODO':
return state.concat([action.text]);
default:
return state;
}
}reducers/status.jsexport default function status(state = {writing: false, error: null}, action) {
switch (action.type) {
case 'ADD_TODO':
return {writing: true, error: null};
case 'ADD_TODO_COMPLETE':
return {writing: false, error: null};
case 'ADD_TODO_FAILED':
return {writing: false, error: action.error};
default:
return state;
}
}reducers/index.jsimport optimist from 'redux-optimist';
import { combineReducers } from 'redux';
import todos from './todos';
import status from './status';
export default optimist(combineReducers({
todos,
status
}));As long as your top-level reducer returns a plain object, you can use optimist. You don't
have to use Redux.combineReducers.
optimist keymiddleware/api.js…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.
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
…MIT
No open issues yet, or sync has not completed.