While solutions like redux thunk exist for dispatching actions asynchronously, I recently encountered a situation like the one below:
import {store} from "./store";
const initialState = {
todos: []
}
function todoApp(state = initialState, action) {
if(action.type == "ACTION_A"){
// 1. do something with state
// 2. do something with state, and then... schedule a dispatch, for example using setTimeout:
setTimeout(()=>store.dispatch({type:"ACTION_B", payload:1}), 2000);
return state;
}// check other actions e.g. ACTION_B etc.
return state;
}
In this example, ACTION_B
is not meant to be dispatched from elsewhere as an async action, but rather is a part of the logic within ACTION_A
.
So, how should such situations be handled in redux?
Some recommend using middleware as a solution, however, comments from Mark Erikson (Redux maintainer) on a blog post suggest that it might not be the right approach. He seems to recommend using redux-loop in such cases.
So, what are the correct ways to deal with such situations in redux? Are there other solutions besides redux-loop? And can redux-thunk still be used to resolve this issue?