What are the advantages of using redux-logic that could be acheived rather than using redux-thunk?
What are the advantages of using redux-logic that could be acheived rather than using redux-thunk?
Redux-thunk is very simple (about 10 lines of code) middleware which allows to dispatch functions. That is all it do.
When dispatching function you can do some other work (inside this function), like fetching data or something else before/after dispatching action (action - means object which will go directly to reducer).
Redux-logic is much more flexible and powerful middleware. It allows to express your intention when writing code.
This sample taken from documentation
const fetchPollsLogic = createLogic({
// declarative built-in functionality wraps your code
type: FETCH_POLLS, // only apply this logic to this type
cancelType: CANCEL_FETCH_POLLS, // cancel on this type
latest: true, // only take latest
// your code here, hook into one or more of these execution
// phases: validate, transform, and/or process
process({ getState, action }, dispatch, done) {
axios.get('https://survey.codewinds.com/polls')
.then(resp => resp.data.polls)
.then(polls => dispatch({ type: FETCH_POLLS_SUCCESS,
payload: polls }))
.catch(err => {
console.error(err); // log since could be render err
dispatch({ type: FETCH_POLLS_FAILED, payload: err,
error: true })
})
.then(() => done()); // call done when finished dispatching
}
});
This sample is fetching data, but it intention and stages (in this case it has only one stage, process) is clear from code.
Doing the same using Redux-thunk will lead to such code
const fetchPollsLogic = () => (dispatch) => {
axios.get('https://survey.codewinds.com/polls')
.then(resp => resp.data.polls)
.then(polls => dispatch({ type: FETCH_POLLS_SUCCESS,
payload: polls }))
.catch(err => {
console.error(err); // log since could be render err
dispatch({ type: FETCH_POLLS_FAILED, payload: err,
error: true })
})
}
The code is essentially the same, but lacks of declarative style, division into stages and so on.
I may recommend to read thru redux-logic, as it much more powerful and flexible compared to redux-thunk