Would there be anything wrong/anti-pattern-ish (in terms of 'thinking-in-react/redux') in added a callback to the action.data
passed into an action?
// reducer
ACTION_FOR_REDUCER() {
var x = 123
if ( action.data.callback ) action.data.callback( x )
return {
something: action.data.somedata
}
},
Then accessing that data later in the App when the action is called (in an container perhaps)
// later in the app
this.props.dispatch(changeSomething({
somedata: somedata,
callback: (x) => { console.log(x) }
}))
Dispatching an action within a reducer is an anti-pattern. Your reducer should be without side effects, simply digesting the action payload and returning a new state object. Adding listeners and dispatching actions within the reducer can lead to chained actions and other side effects.
The redux core package still works, but today we consider it to be obsolete. All of its APIs are also re-exported from @reduxjs/toolkit , and configureStore does everything createStore does but with better default behavior and configurability.
In Redux, a reducer is a pure function that takes an action and the previous state of the application and returns the new state. The action describes what happened and it is the reducer's job to return the new state based on that action. It may seem simple, but it does have to be a pure function with no side effects.
The idea is not wrong, the implementation is.
Instead of adding a callback, return a promise from the action (you will need redux-thunk middleware or some similar alternative).
Then you can simply do:
dispatch(myAction).then(callback);
Of course, you can also simply dispatch another action in your callback, which usually end up being one compound action.
const myAction = ...
const callbackAction = ...
const compoundAction = () => dispatch => {
dispatch(myAction())
.then(() => dispatch(callbackAction()));
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With