Skip to content

Instantly share code, notes, and snippets.

@codejockie
Created February 2, 2021 10:58
Show Gist options
  • Select an option

  • Save codejockie/ddd3f6b16694fba97a91ec3dc09783a1 to your computer and use it in GitHub Desktop.

Select an option

Save codejockie/ddd3f6b16694fba97a91ec3dc09783a1 to your computer and use it in GitHub Desktop.
// Redux basics
// Redux is made up of 3 key parts, namely:
// Store
// Reducer
// Action/ActionCreator
const store = {
cartReducer: {},
profileReducer: {},
};
// User dispatches an action (e.g. via a button click, form submit ...)
// |
// |
// Action
const incrementQuantityAction = {
type: "INCREMENT_QUANTITY",
payload: "some_id",
};
const addToCartAction = {
type: "ADD_TO_CART",
payload: { id: "some_id", productName: "MacBook Pro" /* other properties */ },
};
// Action creator
export function incrementQuantity(itemId) {
return {
type: "INCREMENT_QUANTITY",
payload: itemId,
};
}
export function addItemToCart(item) {
return {
type: "ADD_TO_CART",
payload: item // { id: "some_id", productName: "MacBook Pro" /* other properties */ },
};
}
// Reducer
const initialState = {
items: [],
totalItems: 0,
};
export function cartReducer(state = initialState, action) {
switch (action.type) {
case "ADD_TO_CART":
return {
...state,
items: [...state.items, { ...action.payload, quantity: 1 } /* add new item */],
};
case "INCREMENT_QUANTITY":
return {
...state,
items: state.items.map((item) => {
return item.id === action.payload ? ({ ...item, quantity: item.quantity + 1 }) : item;
}),
};
default:
return state;
}
}
export function profileReducer(state = initialState, action) {}
import { connect, useDispatch, useSelector } from "react-redux";
const Cart = () => {
const dispatch = useDispatch();
const { cart, profile } = useSelector((state) => ({
cart: state.cartReducer,
profile: state.profileReducer,
}));
const handleIncrement = (itemId) => {
dispatch(incrementQuantity(itemId));
};
return (
<>
{cart.items.map((item) => (
<div key={item.id}>
{item.productName}
<span>
<button>&#8722;</button>
{item.quantity}
<button onClick={() => handleIncrement(item.id)}>+</button>
</span>
</div>
))}
</>
);
};
class CartClass extends React.Component {
handleIncrement = (itemId) => {
props.incrementQuantity(itemId);
};
render() {
return (
<>
{props.cart.items.map((item) => (
<div key={item.id}>
{item.productName}
<span>
<button>&#8722;</button>
{item.quantity}
<button onClick={() => handleIncrement(item.id)}>+</button>
</span>
</div>
))}
</>
);
}
}
const mapStateToProps = (state) => {
return {
cart: state.cartReducer,
profile: state.profileReducer,
};
};
const mapDispatchToProps = () => {
return {
incrementQuantity,
};
};
export default connect(mapStateToProps, mapDispatchToProps)(CartClass);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment