summaryrefslogtreecommitdiffstats
path: root/finished-application/frontend/components/RemoveFromCart.js
diff options
context:
space:
mode:
Diffstat (limited to 'finished-application/frontend/components/RemoveFromCart.js')
-rw-r--r--finished-application/frontend/components/RemoveFromCart.js30
1 files changed, 22 insertions, 8 deletions
diff --git a/finished-application/frontend/components/RemoveFromCart.js b/finished-application/frontend/components/RemoveFromCart.js
index d29cbf1..025dae5 100644
--- a/finished-application/frontend/components/RemoveFromCart.js
+++ b/finished-application/frontend/components/RemoveFromCart.js
@@ -1,4 +1,4 @@
-import { Component } from 'react';
+import React from 'react';
import { Mutation } from 'react-apollo';
import styled from 'styled-components';
import PropTypes from 'prop-types';
@@ -23,29 +23,43 @@ const BigButton = styled.button`
}
`;
-class RemoveFromCart extends Component {
+class RemoveFromCart extends React.Component {
static propTypes = {
id: PropTypes.string.isRequired,
};
-
+ // This gets called as soon as we get a response back from the server after a mutation has been performed
update = (cache, payload) => {
+ // 1. first read the cache
const data = cache.readQuery({ query: CURRENT_USER_QUERY });
- // console.log(data.me.cart[0]);
+ // 2. remove that item from the cart
const cartItemId = payload.data.removeFromCart.id;
data.me.cart = data.me.cart.filter(cartItem => cartItem.id !== cartItemId);
+ // 3. write it back to the cache
cache.writeQuery({ query: CURRENT_USER_QUERY, data });
};
-
render() {
return (
<Mutation
mutation={REMOVE_FROM_CART_MUTATION}
variables={{ id: this.props.id }}
update={this.update}
+ optimisticResponse={{
+ __typename: 'Mutation',
+ removeFromCart: {
+ __typename: 'CartItem',
+ id: this.props.id,
+ },
+ }}
>
- {(removeFromCart, { loading }) => (
- <BigButton disabled={loading} title="Remove From Cart" onClick={() => removeFromCart}>
- ×
+ {(removeFromCart, { loading, error }) => (
+ <BigButton
+ disabled={loading}
+ onClick={() => {
+ removeFromCart().catch(err => alert(err.message));
+ }}
+ title="Delete Item"
+ >
+ &times;
</BigButton>
)}
</Mutation>