I am currently trying to work through some example code and have the following in two separate slices:
Reducer in slice 1:
incrementQuantity: (state, action) => {
const { payload: index } = action;
if (state[index]) {
if (state[index].name === " Auditorium Hall (Capacity:200)" && state[index].quantity >= 3) {
return;
}
state[index].quantity++;
}
}
Reducer in slice 2:
toggleMealSelection: (state, action) => {
state[action.payload].selected = !state[action.payload].selected;
},
I don't understand the usage of payload/action in either of the above cases.
Can someone provide a simple explanation what is going on with these two different lines:
const { payload: index } = action;
state[action.payload].selected = !state[action.payload].selected;
const { payload: index } = action;
This uses Javascript's Destructuring Assignment to destructure the action payload
property and rename it to index
.
It's similar to const index = action.payload;
.
const action = { payload: 13 };
const { payload: index1 } = action;
const index2 = action.payload;
console.log({ index1, index2 });
Destructuring assignment is useful when there are several object/array properties/elements you'd like to declare in local scope. Instead of a bunch of const <X> = obj.<X>;
statements, you can use a single const { X, Y, Z, ...rest } = obj;
statement. It helps keep code more DRY and readable.
state[action.payload].selected = !state[action.payload].selected;
This takes the current value stored in state[action.payload].selected
and stores the negated truthy/falsey value back into state[action.payload].selected
. If state[action.payload].selected
is false
, then the result is that state[action.payload].selected
now is true
, and if state[action.payload].selected
is true
, then the result is that state[action.payload].selected
is now false
. value =!value
is a common pattern to flip a boolean.
let value = false;
console.log(value); // false
value = !value // flip false -> true
console.log(value); // true
value = !value // flip true -> false
console.log(value); // false