From ec2cee62547cb9f85f4e97eb02ec1407d95c2ee5 Mon Sep 17 00:00:00 2001 From: Justin Staubach Date: Wed, 2 Oct 2019 00:16:13 -0400 Subject: [PATCH] Fixes #94 Cart empty after reload. Saved cart items to local storage for persistence. --- final/client/src/containers/logout-button.js | 9 +++++++-- final/client/src/index.js | 6 ++++-- final/client/src/pages/login.js | 8 +++++++- final/client/src/resolvers.js | 3 +++ 4 files changed, 21 insertions(+), 5 deletions(-) diff --git a/final/client/src/containers/logout-button.js b/final/client/src/containers/logout-button.js index a4fcdbd0c..f701dc434 100644 --- a/final/client/src/containers/logout-button.js +++ b/final/client/src/containers/logout-button.js @@ -11,8 +11,13 @@ export default function LogoutButton() { { - client.writeData({ data: { isLoggedIn: false } }); - localStorage.clear(); + client.writeData({ + data: { + isLoggedIn: false, + cartItems: [], + }, + }); + localStorage.setItem('token', ''); }} > diff --git a/final/client/src/index.js b/final/client/src/index.js index 7e69da313..7d0f9784f 100644 --- a/final/client/src/index.js +++ b/final/client/src/index.js @@ -29,10 +29,12 @@ const client = new ApolloClient({ typeDefs, }); +const token = localStorage.getItem('token'); +const cart = localStorage.getItem('cart'); cache.writeData({ data: { - isLoggedIn: !!localStorage.getItem('token'), - cartItems: [], + isLoggedIn: !!token, + cartItems: token && cart && JSON.parse(cart)[token] ? JSON.parse(cart)[token] : [], }, }); diff --git a/final/client/src/pages/login.js b/final/client/src/pages/login.js index 9cd70b12e..b6e2c612b 100644 --- a/final/client/src/pages/login.js +++ b/final/client/src/pages/login.js @@ -17,7 +17,13 @@ export default function Login() { { onCompleted({ login }) { localStorage.setItem('token', login); - client.writeData({ data: { isLoggedIn: true } }); + const cart = localStorage.getItem('cart'); + client.writeData({ + data: { + isLoggedIn: true, + cartItems: login && cart && JSON.parse(cart)[login] ? JSON.parse(cart)[login] : [], + }, + }); } } ); diff --git a/final/client/src/resolvers.js b/final/client/src/resolvers.js index 7284ae2fc..99365d4c1 100644 --- a/final/client/src/resolvers.js +++ b/final/client/src/resolvers.js @@ -32,6 +32,9 @@ export const resolvers = { : [...cartItems, id], }; cache.writeQuery({ query: GET_CART_ITEMS, data }); + const token = localStorage.getItem('token'); + const cartObj = JSON.parse(localStorage.getItem('cart')); + localStorage.setItem('cart', JSON.stringify({...cartObj, [token]: data.cartItems})); return data.cartItems; }, },