From b1600adec47a04f60e1da07d94a3ed3906ff5aee Mon Sep 17 00:00:00 2001 From: Wes Bos Date: Thu, 14 Jun 2018 16:44:21 -0400 Subject: starter files --- .../frontend/components/AddToCart.js | 68 ++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 finished-application/frontend/components/AddToCart.js (limited to 'finished-application/frontend/components/AddToCart.js') diff --git a/finished-application/frontend/components/AddToCart.js b/finished-application/frontend/components/AddToCart.js new file mode 100644 index 0000000..03242a4 --- /dev/null +++ b/finished-application/frontend/components/AddToCart.js @@ -0,0 +1,68 @@ +import { Component } from 'react'; +import { Mutation } from 'react-apollo'; +import PropTypes from 'prop-types'; +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 = { + id: PropTypes.string.isRequired, + }; + + update = (cache, payload) => { + const newCartItem = payload.data.addToCart; + const data = cache.readQuery({ query: CURRENT_USER_QUERY }); + + const existingIndex = data.me.cart.findIndex(cartItem => cartItem.id === newCartItem.id); + if (existingIndex >= 0) { + // already in cache, just replace it + data.me.cart = [ + ...data.me.cart.slice(0, existingIndex), + newCartItem, + ...data.me.cart.slice(existingIndex + 1), + ]; + } else { + data.me.cart = [...data.me.cart, newCartItem]; + } + cache.writeQuery({ query: CURRENT_USER_QUERY, data }); + }; + + render() { + const { id } = this.props; + return ( + + {({ data: { me }, loading }) => { + if (!me || loading) return null; + return ( + + {(addToCart, { loading }) => ( + + )} + + ); + }} + + ); + } +} + +export default AddToCart; +export { ADD_TO_CART_MUTATION }; -- cgit v1.3