From 54e39883f8d3e6a3bdb37c9d01d035496485d749 Mon Sep 17 00:00:00 2001 From: Yashrajsinh Jadeja Date: Mon, 17 Jan 2022 14:26:37 +0530 Subject: [PATCH] ISSUE #202 Update quantity on click of add to cart if product already exist in cart --- src/mock-connector/utils/cartStore.js | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/src/mock-connector/utils/cartStore.js b/src/mock-connector/utils/cartStore.js index deb69586..7ebaeb0e 100644 --- a/src/mock-connector/utils/cartStore.js +++ b/src/mock-connector/utils/cartStore.js @@ -3,8 +3,8 @@ import createProduct from './createProduct' const CART_COOKIE = 'rsf_mock_cart' const initialStore = [ - { id: 1, quantity: 1 }, - { id: 2, quantity: 1 }, + { id: '1', quantity: 1 }, + { id: '2', quantity: 1 }, ] function getStore(req, res) { @@ -43,7 +43,12 @@ export function removeItem(id, req, res) { } export function addItem(id, quantity, req, res) { - const newStore = [{ id, quantity }, ...getStore(req, res)] + const currentStore = getStore(req, res); + const isItemExist = currentStore.find((item) => item.id === id); + if (isItemExist !== undefined) { + return updateItem(id, isItemExist.quantity + 1, req, res); + } + const newStore = [{ id, quantity }, ...currentStore] res.setHeader('Set-Cookie', `${CART_COOKIE}=${JSON.stringify(newStore)}; Path=/`) return newStore.map(toProduct) }