Jim Peeters
Jim Peeters

Reputation: 2863

How to change the state of another reducer in react.js redux?

How can I change the state of MenuReducer in SideBarReducer? The meaning of this is to show a warning message in the menu when the user does an action in the sidebar. The user will in the future also do action in other reducers that will cause the warning in the MenuReducer to pop up.

MenuReducer:

import actionTypes from '../action-types';

export const initialState = {
  showWarning: false,
};

export default function MenuReducer(state = initialState, action) {
  switch (action.type) {
    case actionTypes.REQUEST_REFRESH:
      if (action.payload.unsavedChanges) {
        return { ...state, showWarning: true };
      }
    default:
      return state;
  }
}

SidebarReducer:

import actionTypes from '../action-types';

export default function sideBarReducer(state = initialState, action) {
  switch (action.type) {
    case actionTypes.REQUEST_CLOSE:
      if (action.payload.unsavedChanges) {
        // Change the state of MenuReducer
      }
    default:
      return state;
  }
}

Upvotes: 0

Views: 944

Answers (2)

Khalid Azam
Khalid Azam

Reputation: 1643

you should not fire action from another reducer, that's anti-pattern. All action need to fire in React component lifecycle or in action creator.

Reducer is only meant for the state change.

Upvotes: 0

Kinnza
Kinnza

Reputation: 1301

You can create an action that dispatches 2 actions (using Thunk middleware). You can also catch the same action in both reducers and update stuff accordingly.

Upvotes: 1

Related Questions