Reducer methods in RTK's createSlice
method take two arguments. The state
and an action of type PayloadAction. PayloadAction
is a generic type that requires you to pass in the specific type of the payload you are expecting. In our case it's going to be PayloadAction<string>
.
One thing that's really impressive about RTK is that it builds its reducers using immer. Immer allows you to deal with immutable data in a seemingly mutable way. While it appears that we're directly modifying our cart state here, if you hover the state
variable in your IDE you'll see it's actually of type WritableDraft<CartState>
, which means it's a draft of your state. Any changes made there will captured by immer and converted into a single new state object that will replace your current one after your redux method is done running. It's pretty clever and much easier to write than the old redux way of having to make long copies of everything to avoid mutating the redux state directly!
Jamund Ferguson: [0:00] In your IDE, open up cartSlice.ts. In our reducers object, let's add a method called addToCart. Add To Cart is going to take as its first argument the state, and for the second argument will be an action. That's going to be of type Payload Action.
[0:14] Now Payload Action is a special type that we're going to import from the Redux Toolkit. Payload Action takes an argument of the type of the payload that we want to receive. That is going to be in this case a string, which will be the ID of the product we're adding to our cart.
[0:28] Let's pull out that ID and say const ID = action.payload. Then we'll say, state.items ID = 1. If someone clicks Add To Cart, we're going to add one of those to the cart.
[0:41] Now if we want to be able to add more than one we can do a simple check and say, if state.items ID that already exists, then we will say state.items ID ++, so increment the value by one. If it doesn't already exist, then we can set it to one.
[0:56] Now we need to export the action the Redux Toolkit generates here by typing, export const, add to cart = cartSlice.actions. Now open up your Products.tsx file.
[1:09] At the top of the file, we are going to import, addToCart from ../cart/cartSlice. Down in our add to cart button, we're going to add an onClick handler that says onClick = an arrow function and say, dispatch addToCart.
[1:29] Then we need to pass in the current product ID. Now as we click on items in our products page, it's going to add them to our shopping cart.