Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a callback to a Redux Reducer

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) }
}))    
like image 241
Ed Williams Avatar asked Jun 02 '17 09:06

Ed Williams


People also ask

Can I dispatch an action in reducer?

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.

Is Redux deprecated?

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.

How do we return a new state in reducers of Redux?

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.


1 Answers

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()));
};
like image 161
Sulthan Avatar answered Sep 29 '22 00:09

Sulthan