summaryrefslogtreecommitdiffstats
path: root/frontend/components/AddToCart.js
blob: 475729661e4d266905cdb453f94772a72ec0d204 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import { Component } from 'react';
import { Mutation } from 'react-apollo';
import PropTypes from 'prop-types';
import { ADD_TO_CART_MUTATION, CURRENT_USER_QUERY } from '../queries/index';

class AddToCart extends Component {
  static propTypes = {
    id: PropTypes.string.isRequired,
  };

  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() {
    const { id } = this.props;
    return (
      <Mutation mutation={ADD_TO_CART_MUTATION} variables={{ id }} update={this.update}>
        {addToCart => <button onClick={addToCart}>🛒 Add To Cart</button>}
      </Mutation>
    );
  }
}

export default AddToCart;