Professional Documents
Culture Documents
Creating An E-Commerce Site With MERN Stack - Part VI
Creating An E-Commerce Site With MERN Stack - Part VI
Be part of a better internet. Get 20% off membership for a limited time
11
React reducer (Simplifying State Management in React)
React Reducer is a built-in feature of React that allows for a more structured
and centralized approach to managing state within components. It is based
on the concept of the reducer function, inspired by the Redux library, but
designed specifically for React. A reducer function takes in the current state
and an action, and returns a new state based on that action.
A reducer is a pure function that receives two arguments: the current state
and an action object. The state represents the current state of the
application, while the action describes the type of state change to be
performed. Inside the reducer, we use a switch statement to determine the
appropriate action type and update the state accordingly.
Actions are plain JavaScript objects that describe an intention to change the
state. They typically consist of a type property, which indicates the action
type, and optionally, a payload property that carries additional data. Action
types are typically defined as constants to avoid typographical errors.
Make a folder store and create an another folder named cart. This folder
structure help us to organize better if we have multiple reducers.
Inside the cart folder first make the actionType.js where we can export the
action types. We need to add item to the cart, remove item from the cart and
just in case empty the hole cart.
In the cartActions.js define the reducer “skeleton”. The action creators are
functions that create and return action objects, which describe the type of
state change to be performed:
These action creators can be used to dispatch actions within your Redux
application. Dispatching an action triggers the corresponding reducer
function, which updates the state based on the action type.
In the last file we define the reducer function that handle types of actions:
adding item to the cart, removing an item from the cart, and emptying the
cart.
import { ADD_TO_CART, REMOVE_ITEM, EMPTY_CART } from "./actionTypes";
const initState = {
addedItems: [],
total: 0,
};
const cartReducer = (state = initState, action) => {
if (existed_item) {
let updatedItem = { ...existed_item };
updatedItem.quantity =
parseInt(updatedItem.quantity) + parseInt(itemAmount);
return {
...state,
addedItems: updatedAddedItems,
total: state.total + addedItem.price * itemAmount,
};
} else {
addedItem.quantity = parseInt(itemAmount);
//calculating the total
let newTotal = state.total + addedItem.price * itemAmount;
return {
...state,
addedItems: [...state.addedItems, addedItem],
total: newTotal,
};
}
} else if (action.type === REMOVE_ITEM) {
return {
...state,
addedItems: updatedAddedItems,
total: state.total - existed_item.price,
};
} else {
let existed_item = state.addedItems.find(
(item) => action.id === item._id
);
let new_items = state.addedItems.filter((item) => action.id !== item._id);
return {
...state,
addedItems: new_items,
total: newTotal,
};
}
} else if (action.type === EMPTY_CART) {
return {
...state,
addedItems: [],
total: 0,
};
}
return state;
}
};
Make things works update the ProductCard component and use our
reducers. Import the necessary actions and the useDispatch function.
const product_item = {
product: product,
amount: amountInputRef.current.value,
};
dispatch(addToCart(product_item));
};
<Button
variant="contained"
color="primary"
endIcon={<AddShoppingCartIcon />}
last week
part-6
onClick={() => handleAddToCart(product)}
3 weeks ago
part 5
>
+ Add
</Button>
<TextField
inputRef={amountInputRef}
sx={{ width: 70 }}
label="Amount"
id={"amount_" + props.id}
type="number"
min={1}
max={5}
step={1}
defaultValue={1}
/>
Now we made our cart reducer but need to create the CartPage where we can
display our cart data.
The imports various components and icons from the Material-UI library, as
well as external dependencies like React, React Redux, React Router DOM,
and axios.
useEffect(() => {
if (total !== undefined) {
setTotalAmount(`$${total.toFixed(2)}`);
}
}, [total, addedItems, totalAmount]);
const product_item = {
product: item,
amount: 1,
};
dispatch(addToCart(product_item));
};
You already guessed we need to define at the backend the new route for
saving the orders into the database. So let’s go to the backend side and take
the actions.
exports.Order = Order;
await Order.create(newOrder);
res.send("Order saved to the database!");
});
module.exports = router;
If are you here you already made the hard part. Before we can test it, we
must update our navbar:
<IconButton onClick={goToOrders}>
<Badge badgeContent={items.length} color="secondary">
<ShoppingCartIcon />
</Badge>
</IconButton>
{isAdmin && (
<Button color="inherit" onClick={goToAddProduct}>
Add product
</Button>
)}
{!token ? (
<Button color="inherit" onClick={goToLogin}>
Login
</Button>
) : (
<Button color="inherit" onClick={logOut}>
LogOut
</Button>
)}
</Toolbar>
</AppBar>
Well done! The last thing is to add the page to the app.js:
Nice job!
In conclusion, the reducer implemented in the order page provides a crucial
functionality for managing the state of the user’s shopping cart. By utilizing
the addToCart , removeFromCart , and emptyCart actions, the reducer enables
seamless addition, removal, and clearing of items from the cart. The use of
Redux and the useSelector hook allows efficient access to the cart's data
throughout the component. With the help of this reducer, the order page
becomes a powerful tool for users to review, modify, and finalize their
purchases, ensuring a smooth and enjoyable shopping experience.
In the upcoming section, we will be developing the order page, which will
allow logged-in users to view their past orders. See you in Part 7 for more
details.
43 Followers
Hi everyone! I'm an enthusiastic full-stack developer. Please feel free to reach out to me via
email (tokosbex@gmail.com) or Twitter (@tokosbex).
Jan 15 8 1 Apr 25 2
Lists
Stories to Help You Grow as a General Coding Knowledge
Software Developer 20 stories · 1319 saves
19 stories · 1151 saves
Apr 30 1K 28 Feb 16 1
Sudhanshu Dubey in Stackademic Surya Teja
Feb 2 13 2 Jun 6
Help Status About Careers Press Blog Privacy Terms Text to speech Teams