1

There's an action (addOrder) in an orderSlice

orderSlice.js

import { createSlice } from '@reduxjs/toolkit';
const initialState = {
  orders: []
};

const ordersSlice = createSlice({
  name: 'orders',
  initialState,
  reducers: {
    addOrder: {
      reducer: (state, action) => {
        state.orders.push(action.payload)
      },
      prepare: (orderItems, orderTotal) => {
        const orderDate = new Date().toDateString();
        return { payload: { orderDate, orderItems: orderItems, orderTotal: orderTotal }}
      }
    }
  }
})

export const { addOrder } = ordersSlice.actions;
export default ordersSlice.reducer;

I'd like it to also affect the state in another slice (cartSlice). Once the 'addOrder' is fired, it should also bring the cartReducer to its initial state. Some googling suggested that I should use extrareducers for that but I'm really not getting its syntax. See below (not valid code in extrareducers)

cartSlice

import { createSlice } from '@reduxjs/toolkit';
import { addOrder } from './ordersSlice';

const initialState = {
  items: {},
  totalAmount: 0
};

const cartSlice = createSlice({
    name: 'cart',
    initialState: initialState,
    reducers: {
      addToCart: (state, action) => {
        // p = product to be added or amended
        const p = action.payload;
        if (state.items[p.id]) {
          // already exists
          state.items[p.id].quantity += 1;
          state.items[p.id].sum += p.price;
          state.totalAmount += p.price;
        } else {
          state.items[p.id] = { price: p.price, quantity: 1, title: p.title, sum: p.price};
          state.totalAmount += p.price;
        }
      },
      removeFromCart: (state, action) => {
        console.log('remove from cart');
        console.log(action.payload);
        const currentQuantity = state.items[action.payload].quantity;
        console.log(currentQuantity);
        if (currentQuantity > 1) {
          state.items[action.payload].quantity -= 1;
          state.items[action.payload].sum -= state.items[action.payload].price;
          state.totalAmount -= state.items[action.payload].price;
        } else {
          state.totalAmount -= state.items[action.payload].price;
          delete state.items[action.payload];
        }
      }
    },
    extraReducers: (builder) => {
      builder
        .addCase(addOrder(state) => {
          return initialState;
      })
    }
  });

export const { addToCart, removeFromCart } = cartSlice.actions;
export default cartSlice.reducer;
Wasteland
  • 4,889
  • 14
  • 45
  • 91

1 Answers1

2

You're almost there! The builder.addCase function takes two arguments. The first is the action creator and the second is the case reducer. So you need a comma after addOrder.

extraReducers: (builder) => {
  builder.addCase(addOrder, (state) => {
    return initialState;
  });
}
Linda Paiste
  • 38,446
  • 6
  • 64
  • 102