Isaac
Isaac

Reputation: 12874

Possible to update multiple reducer by dispatching single redux action?

Disclaimer: this question is targeting specific package reduxsauce

Takes classic redux action, by dispatching a single action, it will flow thru all the reducer and if we want to update the state, we catch the type in each and every reducer as we see fit

loginPage.js

this.props.memberLogin({ name: 'john' }); //{ type: MEMBER_LOGIN, payload: { name: 'john' } }

LoginAction.js

const memberLogin = member => {
  return { type: MEMBER_LOGIN, payload: member }
}

authReducer.js

const INITIAL_STATE = { isLoggedIn: false }

switch(state = INITIAL_STATE, action) {
  case MEMBER_LOGIN: return { ...state, isLoggedIn: true };
  default: return state;
}

memberReducer.js

const INITIAL_STATE = { member: null }

switch(state = INITIAL_STATE, action) {
  case MEMBER_LOGIN: return { ...state, member: action.payload };
  default: return state;
}

Wondering by using reduxsauce, can we still achieve something similar as demonstrated above? (dispatch single action and update both reducer)

Upvotes: 0

Views: 458

Answers (1)

Bruno Eduardo
Bruno Eduardo

Reputation: 1383

Yes, you can.

I created this Snack example to help you, but the gist is that you have to configure your reducers to listen to the same action.

Kinda like so:

const reduceA = (state, action) => ({
  ...state,
  a: action.value,
});

const reduceB = (state, action) => ({
  ...state,
  b: action.value,
});

const { Types, Creators: actionCreators } = createActions({
  testAction: ['value'],
});


const HANDLERS_A = {
  [Types.TEST_ACTION]: reduceA,
};

const HANDLERS_B = {
  [Types.TEST_ACTION]: reduceB,
};

In the example both reducers A and B have their state values altered by the same action testAction.

Upvotes: 1

Related Questions