Last active
May 6, 2020 17:30
-
-
Save shabbir-ahmed/ef23ca87641de6f7ec8f0b825b89a0ca to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { createStore, applyMiddleware } from 'redux'; | |
import thunk from 'redux-thunk'; | |
import { composeWithDevTools } from 'redux-devtools-extension'; | |
import { | |
ADD_TO_CART, | |
REMOVE_ITEM | |
} from '../actions/action-types/cart-actions' | |
const initState = { | |
products: [ | |
{ | |
id: 1, | |
title: "Long Sleeve Leopard T-Shirt", | |
price: 250, | |
image: require("../../images/products/img1.jpg") | |
}, | |
{ | |
id: 2, | |
title: "Gildan Men's Crew T-Shirt", | |
price: 150, | |
image: require("../../images/products/img4.jpg") | |
}], | |
addedItems:[], | |
total: 0, | |
shipping: 0 | |
} | |
const cartReducer= (state = initState, action) => { | |
if(action.type === ADD_TO_CART){ | |
let addedItem = state.products.find(item => item.id === action.id) | |
//check if the action id exists in the addedItems | |
let existed_item= state.addedItems.find(item=> action.id === item.id) | |
if(existed_item) | |
{ | |
addedItem.quantity += 1 | |
return { | |
...state, | |
total: state.total + addedItem.newPrice | |
} | |
} else { | |
addedItem.quantity = 1; | |
//calculating the total | |
let newTotal = state.total + addedItem.newPrice | |
return { | |
...state, | |
addedItems: [...state.addedItems, addedItem], | |
total : newTotal | |
} | |
} | |
} | |
if(action.type === REMOVE_ITEM){ | |
let itemToRemove= state.addedItems.find(item=> action.id === item.id) | |
let new_items = state.addedItems.filter(item=> action.id !== item.id) | |
//calculating the total | |
let newTotal = state.total - (itemToRemove.newPrice * itemToRemove.quantity ); | |
return { | |
...state, | |
addedItems: new_items, | |
total: newTotal | |
} | |
} | |
else { | |
return state | |
} | |
} | |
export const initStore = (initialState = initState) => { | |
return createStore( | |
cartReducer, | |
initialState, | |
composeWithDevTools(applyMiddleware(thunk)) | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment