Skip to content

Commit

Permalink
Fixes apollographql#94 Cart empty after reload.
Browse files Browse the repository at this point in the history
Saved cart items to local storage for persistence.
  • Loading branch information
JEStaubach committed Oct 2, 2019
1 parent 6988f69 commit ec2cee6
Show file tree
Hide file tree
Showing 4 changed files with 21 additions and 5 deletions.
9 changes: 7 additions & 2 deletions final/client/src/containers/logout-button.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,13 @@ export default function LogoutButton() {
<StyledButton
data-testid="logout-button"
onClick={() => {
client.writeData({ data: { isLoggedIn: false } });
localStorage.clear();
client.writeData({
data: {
isLoggedIn: false,
cartItems: [],
},
});
localStorage.setItem('token', '');
}}
>
<ExitIcon />
Expand Down
6 changes: 4 additions & 2 deletions final/client/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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] : [],
},
});

Expand Down
8 changes: 7 additions & 1 deletion final/client/src/pages/login.js
Original file line number Diff line number Diff line change
Expand Up @@ -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] : [],
},
});
}
}
);
Expand Down
3 changes: 3 additions & 0 deletions final/client/src/resolvers.js
Original file line number Diff line number Diff line change
Expand Up @@ -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;
},
},
Expand Down

0 comments on commit ec2cee6

Please sign in to comment.