blob: e2770cb208b4f08692401806326ce9f3e042348f (
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
35
36
37
38
39
40
41
42
43
44
45
46
47
|
import { Component } from 'react';
import { Mutation, Query } from 'react-apollo';
import PropTypes from 'prop-types';
import { ADD_TO_CART_MUTATION, CURRENT_USER_QUERY } from '../queries/queries';
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 (
<Query query={CURRENT_USER_QUERY}>
{() => (
<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>
)}
</Query>
);
}
}
export default AddToCart;
|