From a6af043686e4375d7944e91cae3d5b63c59edab0 Mon Sep 17 00:00:00 2001 From: Wes Bos Date: Thu, 22 Mar 2018 16:29:31 -0400 Subject: Migrate to render props --- frontend/components/AddToCart.js | 44 +++++++++++++++++++--------------------- 1 file changed, 21 insertions(+), 23 deletions(-) (limited to 'frontend/components/AddToCart.js') diff --git a/frontend/components/AddToCart.js b/frontend/components/AddToCart.js index 22cfe02..4757296 100644 --- a/frontend/components/AddToCart.js +++ b/frontend/components/AddToCart.js @@ -1,36 +1,34 @@ import { Component } from 'react'; -import { graphql, compose } from 'react-apollo'; -import styled from 'styled-components'; +import { Mutation } from 'react-apollo'; import PropTypes from 'prop-types'; -import { removeFromCartEnhancer, userEnhancer, addToCartEnhancer, singleItemEnhancer } from '../enhancers/enhancers'; +import { ADD_TO_CART_MUTATION, CURRENT_USER_QUERY } from '../queries/index'; class AddToCart extends Component { static propTypes = { - currentUser: PropTypes.object.isRequired, + id: PropTypes.string.isRequired, }; - componentDidMount() { - this.props.currentUser.refetch(); - } - - handleAddToCart = async () => { - const res = await this.props.addToCart({ - variables: { - id: this.props.id, - }, - }); + update = (proxy, payload) => { + const newCartItem = payload.data.addToCart; + const data = proxy.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]; + } + proxy.writeQuery({ query: CURRENT_USER_QUERY, data }); }; render() { - return ; + const { id } = this.props; + return ( + + {addToCart => } + + ); } } -AddToCart.propTypes = { - currentUser: PropTypes.object.isRequired, - addToCart: PropTypes.func.isRequired, - id: PropTypes.string.isRequired, -}; - -export default compose(userEnhancer, addToCartEnhancer)(AddToCart); -export { AddToCart }; +export default AddToCart; -- cgit v1.3