Search code examples
reactjsreduxredux-thunk

Redux - Access other reducer's data from the action


in my e-commerce website i'm using react with redux and firebase for storing data and authentication, the user can add items to the cart and then visit the cart component, but after he logs out the items in the cart still the same, so i have to access the state of cardReducer from the authReducer

the auth actions:

export const signOut = () => {
  return (dispatch, getState, {getFirebase}) => {
    const firebase = getFirebase();
    const card = getState().card
    firebase.auth().signOut().then(() => {
      dispatch({ type: 'SIGNOUT_SUCCESS', card })
    });
  }
}

the card reducer:

const initState= []

const cardReducer = (state = initState, action) => {
  switch (action.type) {
    case 'ADD_POST':
      if (!state.includes(action.post)) {
        return [...state, action.post]; 
      }
      return state;
    case 'REMOVE_POST':
      return state.filter(post => post === action.post);
    default: return state;
  }
}

Solution

  • You'll have to add another case for clearing the cart in cardReducer.

    case 'CLEAR_CART':
          return initState;
    

    I assume, you have a cart Actions file too, in that define an action which clears the cart

    export const clearCart = () => {
      return (dispatch) => {
         dispatch({ type: 'CLEAR_CART' })
      }
    }
    

    Then import that action in your auth Actions file, and call the action.

    import { clearCart } from '..Cart Actions Path';
    
    export const signOut = () => {
      return (dispatch, getState, {getFirebase}) => {
        const firebase = getFirebase();
        const card = getState().card
        firebase.auth().signOut().then(() => {
          dispatch({ type: 'SIGNOUT_SUCCESS', card })
          clearCart();
        });
      }
    }