blob: e5e4752892f861e3fa3b0e9852f447ab61a1949f (
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
48
49
50
|
import React, { Component } from 'react';
import { Mutation } from 'react-apollo';
import gql from 'graphql-tag';
import { ALL_ITEMS_QUERY } from './Items';
const DELETE_ITEM_MUTATION = gql`
mutation DELETE_ITEM_MUTATION($id: ID!) {
deleteItem(id: $id) {
id
}
}
`;
class DeleteItem extends Component {
update = (cache, payload) => {
// manually update the cache on the client, so it matches the server
// 1. Read the cache for the items we want
const data = cache.readQuery({ query: ALL_ITEMS_QUERY });
console.log(data, payload);
// 2. Filter the deleted itemout of the page
data.items = data.items.filter(item => item.id !== payload.data.deleteItem.id);
// 3. Put the items back!
cache.writeQuery({ query: ALL_ITEMS_QUERY, data });
};
render() {
return (
<Mutation
mutation={DELETE_ITEM_MUTATION}
variables={{ id: this.props.id }}
update={this.update}
>
{(deleteItem, { error }) => (
<button
onClick={() => {
if (confirm('Are you sure you want to delete this item?')) {
deleteItem().catch(err => {
alert(err.message);
});
}
}}
>
{this.props.children}
</button>
)}
</Mutation>
);
}
}
export default DeleteItem;
|