问题
if I have an async action with api call, which could either be an action returns a function:
export function asyncAction(itemId) {
return (dispatch) => {
dispatch(requestStarted());
return sendRequest(itemId).then(
(result) => dispatch(requestSuccess()),
(error) => dispatch(requestFail())
);
};
}
or one returns an object and uses middleware to intercept it and do stuff:
export function asyncAction(itemId) {
return {
type: [ITEM_REQUEST, ITEM_REQUEST_SUCCESS, ITEM_REQUEST_FAILURE],
promise: sendRequest(itemId),
userId
};
}
// same middleware found in https://github.com/rackt/redux/issues/99
export default function promiseMiddleware() {
return (next) => (action) => {
const { promise, ...rest } = action;
if (!promise) {
return next(action);
}
next({ ...rest, readyState: 'request' );
return promise.then(
(result) => next({ ...rest, result, readyState: 'success' }),
(error) => next({ ...rest, error, readyState: 'failure' })
);
};
}
Now my question is: How do I rollback to the state before the asyncAction is dispatched, which essentially means two steps back in the state(success/failure => request) w/ an api call to undo last api call.
For example, after delete a todo item(which is an async action), a popup snackbar shows with an undo option, after click it the deleted todo item will be added back to UI along with an api call to add it back to db.
I've tried redux-undo but I feel it's not intended to solve problems like this.
Or I should forget about 'undo' and just dispatch a brand new addTodo action when user clicks undo option?
Thanks in advance :-)
回答1:
Redux Optimist might be what you need.
来源:https://stackoverflow.com/questions/33237712/how-to-undo-redux-async-action-multiple-steps-back-in-the-state