diff --git a/src/actions/index.js b/src/actions/index.js index 6ac65d9..018b9ee 100644 --- a/src/actions/index.js +++ b/src/actions/index.js @@ -3,7 +3,7 @@ import { toast } from 'react-toastify'; import axios from '../services/axios'; import types from './types'; -import { saveToken, getToken } from '../utils/localStorage'; +import { saveToken, getToken, removeToken } from '../utils/localStorage'; import jwt from '../utils/jwt'; export const startFetching = () => ({ type: types.START_FETCHING }); @@ -15,6 +15,11 @@ export const stopFetching = (fetchSuccess = true, message = '') => ({ }, }); +export const getCart = () => { + const cart = JSON.parse(localStorage.getItem('cart')) || {}; + return { type: types.GET_CART, payload: cart }; +}; + export const signUpUser = userData => async (dispatch) => { dispatch(startFetching()); try { @@ -50,6 +55,7 @@ export const logInUser = userData => async (dispatch) => { role, }, }); + dispatch(getCart()); return dispatch(stopFetching()); } catch (error) { toast.error(error.response ? error.response.data.message : 'something went wrong'); @@ -100,11 +106,6 @@ export const addToCart = ({ foodId, foodName, foodPrice }) => { return { type: types.ADD_TO_CART_FAIL }; }; -export const getCart = () => { - const cart = JSON.parse(localStorage.getItem('cart')) || {}; - return { type: types.GET_CART, payload: cart }; -}; - export const removeFromCart = (foodId) => { const cart = JSON.parse(localStorage.getItem('cart')) || {}; const updatedCart = omit(cart, foodId); @@ -112,6 +113,8 @@ export const removeFromCart = (foodId) => { return { type: types.REMOVE_FROM_CART, payload: { foodId } }; }; +export const emptyCart = () => ({ type: types.EMPTY_CART }); + export const checkout = foodIds => async (dispatch) => { dispatch(startFetching()); try { @@ -127,3 +130,9 @@ export const checkout = foodIds => async (dispatch) => { ); } }; + +export const logout = () => (dispatch) => { + dispatch(emptyCart()); + removeToken(); + return dispatch({ type: types.LOGOUT }); +}; diff --git a/src/actions/types/index.js b/src/actions/types/index.js index 5410b86..d8376ab 100644 --- a/src/actions/types/index.js +++ b/src/actions/types/index.js @@ -12,4 +12,6 @@ export default { REMOVE_FROM_CART: 'REMOVE_FROM_CART', CHECKOUT: 'CHECKOUT', CHECKOUT_FAIL: 'CHECKOUT_FAIL', + LOGOUT: 'LOGOUT', + EMPTY_CART: 'EMPTY_CART', }; diff --git a/src/components/App.jsx b/src/components/App.jsx index d6beec0..6d3907d 100644 --- a/src/components/App.jsx +++ b/src/components/App.jsx @@ -11,7 +11,7 @@ import Menu from './MenuPage'; import CartPage from './Cart'; import NotFoundPage from './NotFoundPage'; import Loader from './Loader'; -import Nav from './Nav'; +import NavBar from './Nav'; export class App extends Component { async componentDidMount() { @@ -27,7 +27,7 @@ export class App extends Component { {loading && } -