diff options
| author | Randy Ridge <randyridge@gmail.com> | 2018-09-14 20:01:25 -0400 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2018-09-14 20:01:25 -0400 |
| commit | 908180c77cd38011eeedcae949613da2a3391e5e (patch) | |
| tree | b59bf1aae819a04d453cde72f6e601f5561a740f /finished-application/frontend/components/AddToCart.js | |
| parent | 1f6667d233a4a2e9df977204d83a8f749c050c75 (diff) | |
| parent | b3bebda57ba187b7fa10398054b54c05d3fd3555 (diff) | |
Merge branch 'master' into randyridge/our
Diffstat (limited to 'finished-application/frontend/components/AddToCart.js')
| -rw-r--r-- | finished-application/frontend/components/AddToCart.js | 62 |
1 files changed, 15 insertions, 47 deletions
diff --git a/finished-application/frontend/components/AddToCart.js b/finished-application/frontend/components/AddToCart.js index 03242a4..8a71cc3 100644 --- a/finished-application/frontend/components/AddToCart.js +++ b/finished-application/frontend/components/AddToCart.js @@ -1,68 +1,36 @@ -import { Component } from 'react'; +import React from 'react'; import { Mutation } from 'react-apollo'; -import PropTypes from 'prop-types'; import gql from 'graphql-tag'; -import User, { CURRENT_USER_QUERY } from './User'; +import { 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 }); - }; - +class AddToCart extends React.Component { render() { const { id } = this.props; return ( - <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> - ); + <Mutation + mutation={ADD_TO_CART_MUTATION} + variables={{ + id, }} - </User> + refetchQueries={[{ query: CURRENT_USER_QUERY }]} + > + {(addToCart, { loading }) => ( + <button disabled={loading} onClick={addToCart}> + Add{loading && 'ing'} To Cart 🛒 + </button> + )} + </Mutation> ); } } - export default AddToCart; export { ADD_TO_CART_MUTATION }; |
