3

I wanna pass a value from redux state from reducer to another reducer. In my case i want to pass the value of groups from state in groupReducer.js to scheduleReducer.js. I'm using combineReducers from redux to combine between them.

Here's my code: groupReducer.js

...
const initialState = {
groups: [],
...
export default function(state = initialState, action) {
  switch (action.type) {
  case FETCH_GROUPS:
    return {
      ...state,
      groups: action.payload
    };
...

scheduleReducer.js

const initialState = {
  ...
}
...
export default function(state = initialState, action) {
  switch (action.type) {
  case GROUP_INFO:
    return {
      group: groupInfo(action.payload.id, SHOULD_PASS_GROUPS_FETCHED_FROM_GROUPREDUCER)
    };

I want to pass the groups to the last reducer, How can i do this?

Zeyad Etman
  • 2,250
  • 5
  • 25
  • 42

2 Answers2

2

You can use thunk to access complete state object. Get groups from groupReducer and then call your action SHOULD_PASS_GROUPS_FETCHED_FROM_GROUPREDUCER to pass those groups to sheduleReducer.

// thunk action creator, use it as a normal action creator     //
//  while dispatching                                            //
function passGroupFetchedFromGroupReducer() {
  return function (dispatch, getState) {

    // Get state object from getState(). Try console.log(getState() to get 
    // idea of the shape of what getState() returns.

    const groupsToPass = getState().groupReducer.groups;

    // Then dispatch your action with the payload
    dispatch({
     type: 'SHOULD_PASS_GROUPS_FETCHED_FROM_GROUPREDUCER',
     payload: groupsToPass
    })
  };
}

// scheduleReducer.js //
const initialState = {
  groups: [],
  ...
}
...
export default function(state = initialState, action) {
  switch (action.type) {
  case GROUP_INFO:
    return {
      ...state,
      groups: action.payload
  };
}
AkshayM
  • 1,421
  • 10
  • 21
0

You can do something like this.
Get your app's state in action creator and then access the group reducer's state to get groups

const getGroupInfo = () => (dispatch, getState) => {
  const appState = getState();
  const groups = appState.groupReducerKey.groups;
  // code...

  dispatch({
    type: ' GROUP_INFO',
    payload: {
      id:'',
      // any other data
      groups: groups,
    },
  });
};


// scheduleReducer.js
const initialState = {
  ...
}
...
export default function(state = initialState, action) {
  switch (action.type) {
  case GROUP_INFO:
  // access here 
  // action.payload.groups
    return {
      group: groupInfo(action.payload.id, action.payload.groups)
    };
  }
}  

I suggest reading more about sharing data between reducers in redux docs: https://redux.js.org/recipes/structuringreducers/beyondcombinereducers#sharing-data-between-slice-reducers

Murli Prajapati
  • 8,833
  • 5
  • 38
  • 55