From 072eca0e5038a7755ca9b2c94dfe1a0c3f110968 Mon Sep 17 00:00:00 2001 From: Wes Bos Date: Thu, 24 May 2018 15:19:21 -0400 Subject: colocate queries and components --- frontend/components/AddToCart.js | 52 ++++++++++++++++++++++++++-------------- 1 file changed, 34 insertions(+), 18 deletions(-) (limited to 'frontend/components/AddToCart.js') 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 ( - - {(addToCart, { loading }) => ( - - )} - + + {({ data: { me }, loading }) => { + if (!me || loading) return null; + return ( + + {(addToCart, { loading }) => ( + + )} + + ); + }} + ); } } export default AddToCart; +export { ADD_TO_CART_MUTATION }; -- cgit v1.3