diff options
Diffstat (limited to 'frontend/components/AddToCart.js')
| -rw-r--r-- | frontend/components/AddToCart.js | 52 |
1 files changed, 34 insertions, 18 deletions
diff --git a/frontend/components/AddToCart.js b/frontend/components/AddToCart.js index 7cb0856..03242a4 100644 --- a/frontend/components/AddToCart.js +++ b/frontend/components/AddToCart.js @@ -1,10 +1,24 @@ import { Component } from 'react'; import { Mutation } from 'react-apollo'; import PropTypes from 'prop-types'; -import { - ADD_TO_CART_MUTATION, - CURRENT_USER_QUERY, -} from '../queries/queries.graphql'; +import gql from 'graphql-tag'; +import User, { CURRENT_USER_QUERY } from './User'; + +const ADD_TO_CART_MUTATION = gql` + mutation addToCart($id: ID!) { + addToCart(id: $id) { + id + quantity + item { + id + price + description + image + title + } + } + } +`; class AddToCart extends Component { static propTypes = { @@ -15,9 +29,7 @@ class AddToCart extends Component { const newCartItem = payload.data.addToCart; const data = cache.readQuery({ query: CURRENT_USER_QUERY }); - const existingIndex = data.me.cart.findIndex( - cartItem => cartItem.id === newCartItem.id, - ); + const existingIndex = data.me.cart.findIndex(cartItem => cartItem.id === newCartItem.id); if (existingIndex >= 0) { // already in cache, just replace it data.me.cart = [ @@ -34,19 +46,23 @@ class AddToCart extends Component { render() { const { id } = this.props; return ( - <Mutation - mutation={ADD_TO_CART_MUTATION} - variables={{ id }} - update={this.update} - > - {(addToCart, { loading }) => ( - <button disabled={loading} onClick={addToCart}> - 🛒 Add{loading && 'ing'} To Cart - </button> - )} - </Mutation> + <User> + {({ data: { me }, loading }) => { + if (!me || loading) return null; + return ( + <Mutation mutation={ADD_TO_CART_MUTATION} variables={{ id }} update={this.update}> + {(addToCart, { loading }) => ( + <button disabled={loading} onClick={addToCart}> + 🛒 Add{loading && 'ing'} To Cart + </button> + )} + </Mutation> + ); + }} + </User> ); } } export default AddToCart; +export { ADD_TO_CART_MUTATION }; |
