Skip to content

Commit

Permalink
add to cart action added
Browse files Browse the repository at this point in the history
  • Loading branch information
shohan-pherones committed Apr 7, 2023
1 parent 70f09eb commit b66e92a
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 8 deletions.
28 changes: 25 additions & 3 deletions pages/products/[productId].js
Original file line number Diff line number Diff line change
@@ -1,9 +1,24 @@
import { useCallback, useState } from "react";
import { getProduct } from "@/prisma/products";
import { addToCart } from "@/store/productSlice";
import { useDispatch } from "react-redux";
import { formatCurrency } from "@/utils/formatCurrency";
import Image from "next/image";
import Link from "next/link";

const ProductDetails = ({ product }) => {
const [quantity, setQuantity] = useState(1);

const handleDecrease = useCallback(() => {
setQuantity(quantity === 1 ? 1 : (prev) => prev - 1);
}, [quantity]);

const handleIncrease = useCallback(() => {
setQuantity((prev) => prev + 1);
}, []);

const dispatch = useDispatch();

return (
<div className="wrapper my-10 grid lg:grid-cols-2 gap-10">
<Image
Expand All @@ -27,18 +42,25 @@ const ProductDetails = ({ product }) => {
{formatCurrency(product.price)}
</p>
<div className="counter flex items-center bg-gray-100 text-2xl">
<button className="bg-gray-700 text-white h-10 w-10 flex items-center justify-center hover:bg-cyan-500 duration-300">
<button
onClick={handleDecrease}
className="bg-gray-700 text-white h-10 w-10 flex items-center justify-center hover:bg-cyan-500 duration-300"
>
-
</button>
<span className="h-10 w-10 flex items-center justify-center">
5
{quantity}
</span>
<button className="bg-gray-700 text-white h-10 w-10 flex items-center justify-center hover:bg-cyan-500 duration-300">
<button
onClick={handleIncrease}
className="bg-gray-700 text-white h-10 w-10 flex items-center justify-center hover:bg-cyan-500 duration-300"
>
+
</button>
</div>
</div>
<Link
onClick={() => dispatch(addToCart({ ...product, quantity }))}
href="/"
className="bg-cyan-500 text-center py-3 text-white text-xl font-medium hover:bg-cyan-600 duration-300 mt-5"
>
Expand Down
20 changes: 15 additions & 5 deletions store/productSlice.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,25 @@
import { createSlice } from "@reduxjs/toolkit";

const initialState = {
products: localStorage.getItem("products")
? JSON.parse(localStorage.getItem("products"))
: [],
products: [],
};

export const productSlice = createSlice({
name: "products",
initialState,
reducers: {},
reducers: {
addToCart: (state, action) => {
const item = state.products.find(
(product) => product.id === action.payload.id
);

if (item) {
item.quantity += action.payload.quantity;
} else {
state.products.push(action.payload);
}
},
},
});

export const {} = productSlice.actions;
export const { addToCart } = productSlice.actions;

0 comments on commit b66e92a

Please sign in to comment.