Skip to content

Commit

Permalink
Merge 403a6b4 into 511e47e
Browse files Browse the repository at this point in the history
  • Loading branch information
akhilome committed Feb 6, 2019
2 parents 511e47e + 403a6b4 commit 5467fbd
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 6 deletions.
19 changes: 13 additions & 6 deletions src/actions/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,14 @@ import { toast } from 'react-toastify';

import axios from '../services/axios';
import types from './types';
import { saveToken, getToken, removeToken } from '../utils/localStorage';
import {
saveToken,
getToken,
removeToken,
getCartItems,
updateCartItems,
clearCartItems,
} from '../utils/localStorage';
import jwt from '../utils/jwt';

const errorResponse = ({ response }) => (response ? response.data.message : 'something went wrong');
Expand Down Expand Up @@ -90,10 +97,10 @@ export const getMenu = () => async (dispatch) => {

export const addToCart = ({ foodId, foodName, foodPrice }) => {
const foodDetails = { [foodId]: { foodName, foodPrice } };
const cart = JSON.parse(localStorage.getItem('cart')) || {};
const cart = getCartItems();
if (!Object.keys(cart).includes(`${foodId}`)) {
const updatedCart = { ...cart, ...foodDetails };
localStorage.setItem('cart', JSON.stringify(updatedCart));
updateCartItems(updatedCart);
toast.success(`${foodName} added to cart 🚀`);
return { type: types.ADD_TO_CART, payload: foodDetails };
}
Expand All @@ -102,9 +109,9 @@ export const addToCart = ({ foodId, foodName, foodPrice }) => {
};

export const removeFromCart = (foodId) => {
const cart = JSON.parse(localStorage.getItem('cart')) || {};
const cart = getCartItems();
const updatedCart = omit(cart, foodId);
localStorage.setItem('cart', JSON.stringify(updatedCart));
updateCartItems(updatedCart);
return { type: types.REMOVE_FROM_CART, payload: { foodId } };
};

Expand All @@ -114,7 +121,7 @@ export const checkout = foodIds => async (dispatch) => {
dispatch(startFetching());
try {
await axios.post('/orders', { foodIds });
localStorage.removeItem('cart');
clearCartItems();
dispatch({ type: types.CHECKOUT });
toast.success('Order placed! 🎉');
return dispatch(stopFetching());
Expand Down
3 changes: 3 additions & 0 deletions src/utils/localStorage.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,6 @@ export const saveToken = (token) => {

export const getToken = () => window.localStorage.getItem('kiakiafoodToken') || '';
export const removeToken = () => window.localStorage.removeItem('kiakiafoodToken');
export const getCartItems = () => JSON.parse(window.localStorage.getItem('cart')) || {};
export const updateCartItems = updatedCart => window.localStorage.setItem('cart', JSON.stringify(updatedCart));
export const clearCartItems = () => window.localStorage.removeItem('cart');

0 comments on commit 5467fbd

Please sign in to comment.