Skip to content

Commit

Permalink
worked with useReducer
Browse files Browse the repository at this point in the history
  • Loading branch information
Ahesh-A committed Jan 7, 2023
1 parent 4373ec3 commit f2162fc
Show file tree
Hide file tree
Showing 4 changed files with 256 additions and 98 deletions.
183 changes: 110 additions & 73 deletions src/contexts/cart.context.jsx
Original file line number Diff line number Diff line change
@@ -1,89 +1,126 @@
import { createContext, useState, useEffect } from 'react';

import { createContext, useReducer } from "react";
import { createAction } from "../utils/reducer/reducer.util";
const addCartItem = (items, productToAdd) => {

const existingCartItem = items.find((item) => item.id === productToAdd.id);
if (existingCartItem) {
return items.map((item) =>
item.id === productToAdd.id
? { ...item, quantity: item.quantity + 1 } :
item);
}
return [...items, { ...productToAdd, quantity: 1 }];
}
const decreaseCartItem = (cartItems, cartItemToRemove) => {
// find the cart item to remove
const existingCartItem = cartItems.find(
(cartItem) => cartItem.id === cartItemToRemove.id
const existingCartItem = items.find((item) => item.id === productToAdd.id);
if (existingCartItem) {
return items.map((item) =>
item.id === productToAdd.id
? { ...item, quantity: item.quantity + 1 }
: item
);
}
return [...items, { ...productToAdd, quantity: 1 }];
};
const decreaseCartItem = (cartItems, cartItemToRemove) => {
// find the cart item to remove
const existingCartItem = cartItems.find(
(cartItem) => cartItem.id === cartItemToRemove.id
);

// check if quantity is equal to 1, if it is remove that item from the cart
if (existingCartItem.quantity === 1) {
return cartItems.filter((cartItem) => cartItem.id !== cartItemToRemove.id);
}
// check if quantity is equal to 1, if it is remove that item from the cart
if (existingCartItem.quantity === 1) {
return cartItems.filter((cartItem) => cartItem.id !== cartItemToRemove.id);
}

// return back cartitems with matching cart item with reduced quantity
return cartItems.map((cartItem) =>
cartItem.id === cartItemToRemove.id
? { ...cartItem, quantity: cartItem.quantity - 1 }
: cartItem
);
// return back cartitems with matching cart item with reduced quantity
return cartItems.map((cartItem) =>
cartItem.id === cartItemToRemove.id
? { ...cartItem, quantity: cartItem.quantity - 1 }
: cartItem
);
};

const removeCartItem = (cartItems, cartItemToClear) =>
cartItems.filter((cartItem) => cartItem.id !== cartItemToClear.id);
cartItems.filter((cartItem) => cartItem.id !== cartItemToClear.id);

export const CartContext = createContext(
{
isopen: false,
setIsopen: () => null,
items: [],
addItemsToCart: () => { },
decreaseCartItem: () => { },
removeCartItem: () => { },
count: 0
}
);
export const CartContext = createContext({
isopen: false,
setIsopen: () => null,
items: [],
addItemsToCart: () => {},
decreaseCartItem: () => {},
removeCartItem: () => {},
count: 0,
});

export const CartProvider = ({ children }) => {
const CART_ACTION_TYPES = {
SET_CART_ITEMS: "SET_CART_ITEMS",
TOGGLE: "TOGGLE",
};
const INITIAL_STATE = {
isopen: false,
items: [],
count: 0,
cartTotal: 0,
};

const addItemsToCart = (productToAdd) => {
setItems(addCartItem(items, productToAdd));
}
const cartReducer = (state, action) => {
const { type, payload } = action;

const removeItemsFromCart = (productToRemove) => {
setItems(removeCartItem(items, productToRemove));
}
switch (type) {
case CART_ACTION_TYPES.SET_CART_ITEMS:
case CART_ACTION_TYPES.TOGGLE:
return {
...state,
...payload,
};
default:
throw new Error(`unhandled type of ${type} in cart reducer`);
}
};

export const CartProvider = ({ children }) => {
const [{ items, isopen, count, cartTotal }, dispatch] = useReducer(
cartReducer,
INITIAL_STATE
);

const setIsopen = () => {
dispatch(createAction(CART_ACTION_TYPES.TOGGLE, { isopen: !isopen }));
};

const decreaseItemsFromCart = (productToDecrease) => {
const res = decreaseCartItem(items, productToDecrease);
console.log(res);
setItems(res);
}
const updateCartItemsReducer = (newCartItems) => {
const newCartCount = items.reduce(
(accumulator, currentValue) => accumulator + currentValue.quantity,
0
);

const [isopen, setIsopen] = useState(false);
const [items, setItems] = useState([]);
const [count, setCount] = useState(0);
const [cartTotal, setCartTotal] = useState(0);
const value = {
isopen, setIsopen, items,
addItemsToCart, count, removeItemsFromCart,
decreaseItemsFromCart, cartTotal
}
const newCartTotal = items.reduce(
(total, cartItem) => total + cartItem.quantity * cartItem.price,
0
);
dispatch(
createAction(CART_ACTION_TYPES.SET_CART_ITEMS, {
items: newCartItems,
cartTotal: newCartTotal,
count: newCartCount,
})
);
};

useEffect(() => {
const total = items.reduce((accumulator, currentValue) => accumulator + currentValue.quantity, 0);
setCount(total);
}, [items]);
const addItemsToCart = (productToAdd) => {
const newCartItems = addCartItem(items, productToAdd);
updateCartItemsReducer(newCartItems);
};

useEffect(() => {
const newCartTotal = items.reduce((total, cartItem) => total + cartItem.quantity * cartItem.price, 0);
setCartTotal(newCartTotal);
}, [items]);
const removeItemsFromCart = (productToRemove) => {
const newCartItems = removeCartItem(items, productToRemove);
updateCartItemsReducer(newCartItems);
};

return (
<CartContext.Provider value={value}>
{children}
</CartContext.Provider>
)
}
const decreaseItemsFromCart = (productToDecrease) => {
const newCartItems = decreaseCartItem(items, productToDecrease);
updateCartItemsReducer(newCartItems);
};
const value = {
isopen,
setIsopen,
items,
addItemsToCart,
count,
removeItemsFromCart,
decreaseItemsFromCart,
cartTotal,
};
return <CartContext.Provider value={value}>{children}</CartContext.Provider>;
};
89 changes: 89 additions & 0 deletions src/contexts/mycart.context.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
import { createContext, useState, useEffect } from 'react';

const addCartItem = (items, productToAdd) => {

const existingCartItem = items.find((item) => item.id === productToAdd.id);
if (existingCartItem) {
return items.map((item) =>
item.id === productToAdd.id
? { ...item, quantity: item.quantity + 1 } :
item);
}
return [...items, { ...productToAdd, quantity: 1 }];
}
const decreaseCartItem = (cartItems, cartItemToRemove) => {
// find the cart item to remove
const existingCartItem = cartItems.find(
(cartItem) => cartItem.id === cartItemToRemove.id
);

// check if quantity is equal to 1, if it is remove that item from the cart
if (existingCartItem.quantity === 1) {
return cartItems.filter((cartItem) => cartItem.id !== cartItemToRemove.id);
}

// return back cartitems with matching cart item with reduced quantity
return cartItems.map((cartItem) =>
cartItem.id === cartItemToRemove.id
? { ...cartItem, quantity: cartItem.quantity - 1 }
: cartItem
);
};

const removeCartItem = (cartItems, cartItemToClear) =>
cartItems.filter((cartItem) => cartItem.id !== cartItemToClear.id);

export const CartContext = createContext(
{
isopen: false,
setIsopen: () => null,
items: [],
addItemsToCart: () => { },
decreaseCartItem: () => { },
removeCartItem: () => { },
count: 0
}
);

export const CartProvider = ({ children }) => {

const addItemsToCart = (productToAdd) => {
setItems(addCartItem(items, productToAdd));
}

const removeItemsFromCart = (productToRemove) => {
setItems(removeCartItem(items, productToRemove));
}

const decreaseItemsFromCart = (productToDecrease) => {
const res = decreaseCartItem(items, productToDecrease);
console.log(res);
setItems(res);
}

const [isopen, setIsopen] = useState(false);
const [items, setItems] = useState([]);
const [count, setCount] = useState(0);
const [cartTotal, setCartTotal] = useState(0);
const value = {
isopen, setIsopen, items,
addItemsToCart, count, removeItemsFromCart,
decreaseItemsFromCart, cartTotal
}

useEffect(() => {
const total = items.reduce((accumulator, currentValue) => accumulator + currentValue.quantity, 0);
setCount(total);
}, [items]);

useEffect(() => {
const newCartTotal = items.reduce((total, cartItem) => total + cartItem.quantity * cartItem.price, 0);
setCartTotal(newCartTotal);
}, [items]);

return (
<CartContext.Provider value={value}>
{children}
</CartContext.Provider>
)
}
81 changes: 56 additions & 25 deletions src/contexts/user.context.jsx
Original file line number Diff line number Diff line change
@@ -1,32 +1,63 @@
import { createContext, useState, useEffect } from 'react';
import { onAuthStateChangedListener, cerateUserDocumentFromAuth } from '../utils/firebase/firebse.utils';
import { createContext, useEffect, useReducer } from "react";
import {
onAuthStateChangedListener,
cerateUserDocumentFromAuth,
} from "../utils/firebase/firebse.utils";
import { createAction } from "../utils/reducer/reducer.util";
// as the actula value we want to access
export const UserContext = createContext({
currentUser: null,
setCurrentUser: () => null

export const UserContext = createContext({
currentUser: null,
setCurrentUser: () => null,
});

export const UserProvider = ({ children }) => {
const [currentUser, setCurrentUser] = useState(null);
const value = { currentUser, setCurrentUser };

useEffect(() => {
const unSubscribe = onAuthStateChangedListener((user) => {
if (user) {
cerateUserDocumentFromAuth(user);
}
setCurrentUser(user);
});


return unSubscribe;
}, []);
return (
<UserContext.Provider value={value}>
{children}
</UserContext.Provider>
);
export const USER_ACTION_TYPES = {
SET_CURRENT_USER: "SET_CURRENT_USER ",
};

const userReducer = (state, action) => {
const { type, payload } = action;
console.log("dispached");
console.log(action);

switch (type) {
case USER_ACTION_TYPES.SET_CURRENT_USER:
return {
...state,
currentUser: payload,
};

default:
throw new Error(`unhandled type ${type} in userReducer`);
}
};

const INITIAL_STATE = {
currentUser: null,
};

export const UserProvider = ({ children }) => {
//const [currentUser, setCurrentUser] = useState(null);
const [{ currentUser }, dispatch] = useReducer(userReducer, INITIAL_STATE);

console.log(currentUser);

const setCurrentUser = (user) => {
dispatch(createAction(USER_ACTION_TYPES.SET_CURRENT_USER, user));
};

const value = { currentUser, setCurrentUser };

useEffect(() => {
const unSubscribe = onAuthStateChangedListener((user) => {
if (user) {
cerateUserDocumentFromAuth(user);
}
setCurrentUser(user);
});

return unSubscribe;
}, []);

return <UserContext.Provider value={value}>{children}</UserContext.Provider>;
};
1 change: 1 addition & 0 deletions src/utils/reducer/reducer.util.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export const createAction = (type, payload) => ({type, payload});

0 comments on commit f2162fc

Please sign in to comment.