summaryrefslogtreecommitdiffstats
path: root/finished-application/frontend/components/DeleteItem.js
diff options
context:
space:
mode:
authorWes Bos <wesbos@gmail.com>2018-06-14 16:44:21 -0400
committerWes Bos <wesbos@gmail.com>2018-06-14 16:44:21 -0400
commitb1600adec47a04f60e1da07d94a3ed3906ff5aee (patch)
tree828f786da6806d7237ee5cbc5df61e552353b85b /finished-application/frontend/components/DeleteItem.js
parenta95e08cd2dd5d7ec0a0412adae02515a5f9cec4f (diff)
starter files
Diffstat (limited to 'finished-application/frontend/components/DeleteItem.js')
-rw-r--r--finished-application/frontend/components/DeleteItem.js71
1 files changed, 71 insertions, 0 deletions
diff --git a/finished-application/frontend/components/DeleteItem.js b/finished-application/frontend/components/DeleteItem.js
new file mode 100644
index 0000000..4d68d5e
--- /dev/null
+++ b/finished-application/frontend/components/DeleteItem.js
@@ -0,0 +1,71 @@
+import React from 'react';
+import { Mutation } from 'react-apollo';
+import PropTypes, { number } from 'prop-types';
+import gql from 'graphql-tag';
+import { withRouter } from 'next/router';
+import { ALL_ITEMS_QUERY } from './Items';
+import { PAGINATION_QUERY } from './Pagination';
+import { perPage } from '../config';
+
+const DELETE_ITEM_MUTATION = gql`
+ mutation deleteItem($id: ID!) {
+ deleteItem(id: $id) {
+ id
+ title
+ description
+ }
+ }
+`;
+
+class DeleteItem extends React.Component {
+ static propTypes = {
+ id: PropTypes.string.isRequired,
+ };
+
+ update = (cache, payload) => {
+ const deletedItem = payload.data.deleteItem;
+ let { page = 1 } = this.props.router.query;
+ page = parseFloat(page);
+ const skip = page * perPage - perPage;
+ const variables = { skip };
+ const data = cache.readQuery({ query: ALL_ITEMS_QUERY, variables });
+ // filter this one out
+ data.items = data.items.filter(item => item.id !== deletedItem.id);
+ // write the data back to the cache
+ console.log(data.items);
+ cache.writeQuery({ query: ALL_ITEMS_QUERY, data, variables });
+ // FYI Pagination is broken with Apollo currently - will make a followup video
+ };
+
+ render() {
+ return (
+ <Mutation
+ mutation={DELETE_ITEM_MUTATION}
+ variables={{ id: this.props.id }}
+ refetchQueries={[
+ {
+ query: ALL_ITEMS_QUERY,
+ variables: { skip: (this.props.router.query.page || 1) * perPage - perPage },
+ },
+ { query: PAGINATION_QUERY },
+ ]}
+ update={this.update}
+ >
+ {(removeItem, { error }) => (
+ <button
+ onClick={() => {
+ if (confirm('Are you sure you want to delete this item?')) {
+ removeItem();
+ }
+ }}
+ >
+ {error ? error.message : '× Delete Item'}
+ </button>
+ )}
+ </Mutation>
+ );
+ }
+}
+
+export default withRouter(DeleteItem);
+export { DELETE_ITEM_MUTATION };