Skip to content

Commit ec2cee6

Browse files
committed
Fixes #94 Cart empty after reload.
Saved cart items to local storage for persistence.
1 parent 6988f69 commit ec2cee6

File tree

4 files changed

+21
-5
lines changed

4 files changed

+21
-5
lines changed

final/client/src/containers/logout-button.js

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,13 @@ export default function LogoutButton() {
1111
<StyledButton
1212
data-testid="logout-button"
1313
onClick={() => {
14-
client.writeData({ data: { isLoggedIn: false } });
15-
localStorage.clear();
14+
client.writeData({
15+
data: {
16+
isLoggedIn: false,
17+
cartItems: [],
18+
},
19+
});
20+
localStorage.setItem('token', '');
1621
}}
1722
>
1823
<ExitIcon />

final/client/src/index.js

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,10 +29,12 @@ const client = new ApolloClient({
2929
typeDefs,
3030
});
3131

32+
const token = localStorage.getItem('token');
33+
const cart = localStorage.getItem('cart');
3234
cache.writeData({
3335
data: {
34-
isLoggedIn: !!localStorage.getItem('token'),
35-
cartItems: [],
36+
isLoggedIn: !!token,
37+
cartItems: token && cart && JSON.parse(cart)[token] ? JSON.parse(cart)[token] : [],
3638
},
3739
});
3840

final/client/src/pages/login.js

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,13 @@ export default function Login() {
1717
{
1818
onCompleted({ login }) {
1919
localStorage.setItem('token', login);
20-
client.writeData({ data: { isLoggedIn: true } });
20+
const cart = localStorage.getItem('cart');
21+
client.writeData({
22+
data: {
23+
isLoggedIn: true,
24+
cartItems: login && cart && JSON.parse(cart)[login] ? JSON.parse(cart)[login] : [],
25+
},
26+
});
2127
}
2228
}
2329
);

final/client/src/resolvers.js

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,9 @@ export const resolvers = {
3232
: [...cartItems, id],
3333
};
3434
cache.writeQuery({ query: GET_CART_ITEMS, data });
35+
const token = localStorage.getItem('token');
36+
const cartObj = JSON.parse(localStorage.getItem('cart'));
37+
localStorage.setItem('cart', JSON.stringify({...cartObj, [token]: data.cartItems}));
3538
return data.cartItems;
3639
},
3740
},

0 commit comments

Comments
 (0)