|
| 1 | +import React from 'react'; |
| 2 | +import { Mutation } from 'react-apollo'; |
| 3 | +import styled from 'styled-components'; |
| 4 | +import PropTypes from 'prop-types'; |
| 5 | +import gql from 'graphql-tag'; |
| 6 | +import { CURRENT_USER_QUERY } from './User'; |
| 7 | + |
| 8 | +const REMOVE_FROM_CART_MUTATION = gql` |
| 9 | + mutation removeFromCart($id: ID!) { |
| 10 | + removeFromCart(id: $id) { |
| 11 | + id |
| 12 | + } |
| 13 | + } |
| 14 | +`; |
| 15 | + |
| 16 | +const BigButton = styled.button` |
| 17 | + font-size: 3rem; |
| 18 | + background: none; |
| 19 | + border: 0; |
| 20 | + &:hover { |
| 21 | + color: ${props => props.theme.red}; |
| 22 | + cursor: pointer; |
| 23 | + } |
| 24 | +`; |
| 25 | + |
| 26 | +class RemoveFromCart extends React.Component { |
| 27 | + static propTypes = { |
| 28 | + id: PropTypes.string.isRequired, |
| 29 | + }; |
| 30 | + // This gets called as soon as we get a response back from the server after a mutation has been performed |
| 31 | + update = (cache, payload) => { |
| 32 | + console.log('Running remove from cart update fn'); |
| 33 | + // 1. first read the cache |
| 34 | + const data = cache.readQuery({ query: CURRENT_USER_QUERY }); |
| 35 | + console.log(data); |
| 36 | + // 2. remove that item from the cart |
| 37 | + const cartItemId = payload.data.removeFromCart.id; |
| 38 | + data.me.cart = data.me.cart.filter(cartItem => cartItem.id !== cartItemId); |
| 39 | + // 3. write it back to the cache |
| 40 | + cache.writeQuery({ query: CURRENT_USER_QUERY, data }); |
| 41 | + }; |
| 42 | + render() { |
| 43 | + return ( |
| 44 | + <Mutation |
| 45 | + mutation={REMOVE_FROM_CART_MUTATION} |
| 46 | + variables={{ id: this.props.id }} |
| 47 | + update={this.update} |
| 48 | + optimisticResponse={{ |
| 49 | + __typename: 'Mutation', |
| 50 | + removeFromCart: { |
| 51 | + __typename: 'CartItem', |
| 52 | + id: this.props.id, |
| 53 | + }, |
| 54 | + }} |
| 55 | + > |
| 56 | + {(removeFromCart, { loading, error }) => ( |
| 57 | + <BigButton |
| 58 | + disabled={loading} |
| 59 | + onClick={() => { |
| 60 | + removeFromCart().catch(err => alert(err.message)); |
| 61 | + }} |
| 62 | + title="Delete Item" |
| 63 | + > |
| 64 | + × |
| 65 | + </BigButton> |
| 66 | + )} |
| 67 | + </Mutation> |
| 68 | + ); |
| 69 | + } |
| 70 | +} |
| 71 | + |
| 72 | +export default RemoveFromCart; |
0 commit comments