TilikWebDeloper
TilikWebDeloper

Reputation: 219

change state in another reducer

i started to study the react. here is my problem. I have some reducers

let reducers = combineReducers({
    user: userReducer,
    index_page: indexReducer,
    notifications: notificationsReducer
});

Notifications Reducer has its own state of notifications for their renderingand in indexReducer there is. An axios request which, after the response, should draw a notification to the user - change state in notificationsReducer.

I do not quite understand how to do this.

This is my code:

notificationsReducer

let initialState = [
    {id: 3, text: 'test_msg', state: 'error'}
];

export const createNotificationActionCreator = (msg_text, msg_state) => {
    return {
        type: 'SHOW_NOTIFY',
        msg_text: msg_text,
        msg_state: msg_state
    }
}

const notificationsReducer = (state = initialState, action) => {
    switch (action.type) {
        case SHOW_NOTIFY:

            let msg = {
                text: action.msg_text,
                msg_state: action.msg_state
            };

            state.push(msg);
            break;
    }

    return state;
}

indexReducer

const indexReducer = (state = initialState, action) => {
   switch (action.type) {
       case CREATE_NEW_BET:
           let bet_data = new Object();

           bet_data.bet = state.betAmount;
           bet_data.color = action.color;

           axios.get('http://localhost/createbet', {
               params: {
                   bet_data
               }
           }).then(function (response) {
               // CHANGE STATE IN notificationsReducer
           });

           break;
   }

   return state;
}

Upvotes: 0

Views: 692

Answers (1)

Robert Cooper
Robert Cooper

Reputation: 2250

To update state in another reducer, I would suggest dispatching the SHOW_NOTIFY action right after dispatching the CREATE_NEW_BET. This can be done using Redux Thunks.

Also read this Stack Overflow answer on suggestions to update state managed by another reducer: Updating state managed by another reducer

With redux-thunk setup, this is what your thunk would look like:

const createBetAndNotify = () => (dispatch) => {
  return dispatch({ type: "CREATE_NEW_BET" }).then(() => {
    dispatch({ type: "SHOW_NOTIFY" })
  })
}

Then inside your React component, you would dispatch the above thunk:

dispatch(createBetAndNotify());

Upvotes: 1

Related Questions