Search code examples
reactjsreduxreact-reduxredux-sagaimmutable.js

How can I use "home" state within "global" reducer?


I have a react, redux-saga, immutable js app.

With this architecture, my redux store is like this.

global: {
   notifications:{...}
   ...
},
home: {
   ...contents
}

The problem is when I want to update home contents i am using a reducer attached to the home. But inside the home reducer, notifications is not available. Because notifications is inside global.

Just the opposite of this approach is using the global reducer, notifications are available at the global state. But this time I can not access the home > contents

My code is below.

This is the reducer attached to global:

case CONTENT_ADD_SUCCESS:
  return state
    .set('loading', false)
    .update('notifications', arr => arr.push(
      fromJS(
      {
        show: true,
        type: 'success',
        message: action.response.message,
      }
    )
   .setIn(['home', 'contents'], action.response.newContent)
  ))

Global Reducer Injection

const withReducer = injectReducer({ key: 'global', reducer });
const withSaga = injectSaga({ key: 'global', saga });

export default compose(
  withReducer,
  withSaga,
  withConnect,
)(withStyles(mainLayoutStyle)(MainLayout));

How can I use different reducer states? For this example, I want to access global notifications and also update home content.


Solution

  • I didn't know that I can use the same constant for different reducers.

    Basically I attached another reducer, a home reducer to the same constant.

    Below is my code: This is for layout reducer. managing notifications with CONTENT_ADD_SUCCESS

    case CONTENT_ADD_SUCCESS:
            return state
                .set('loading', false)
                .update('notifications', arr => arr.push(
                    fromJS(
                        {
                            key: CONTENT_ADD_SUCCESS_N_ID,
                            show: true,
                            type: 'success',
                            message: action.response.message,
                        }
                    )
                ))
    

    This one for home reducer managing home contents with CONTENT_ADD_SUCCESS

    case CONTENT_ADD_SUCCESS:
            console.log('HOME REDUCER :: CONTENT_ADD_SUCCESS', state);
            return state
              .update('contents', arr => arr.unshift(fromJS(JSON.parse(action.response.newContent))))