diff options
| author | Wes Bos <wesbos@gmail.com> | 2018-06-14 16:44:21 -0400 |
|---|---|---|
| committer | Wes Bos <wesbos@gmail.com> | 2018-06-14 16:44:21 -0400 |
| commit | b1600adec47a04f60e1da07d94a3ed3906ff5aee (patch) | |
| tree | 828f786da6806d7237ee5cbc5df61e552353b85b /finished-application/frontend/components/AddToCart.js | |
| parent | a95e08cd2dd5d7ec0a0412adae02515a5f9cec4f (diff) | |
starter files
Diffstat (limited to 'finished-application/frontend/components/AddToCart.js')
| -rw-r--r-- | finished-application/frontend/components/AddToCart.js | 68 |
1 files changed, 68 insertions, 0 deletions
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 ( + <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 }; |
