-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathArticles.tsx
54 lines (48 loc) · 1.29 KB
/
Articles.tsx
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
51
52
53
54
import React from 'react';
import { useQuery, gql, useMutation } from '@apollo/client';
import { Link } from 'react-router-dom';
const getArticlesQuery = gql`
query getArticles {
articles {
id
title
}
}
`;
const removeArticleMutation = gql`
mutation removeArticle($id: ID!) {
removeArticle(id: $id)
}
`;
function Articles() {
const {data} = useQuery(getArticlesQuery);
const [removeArticle] = useMutation(removeArticleMutation, {
update(cache, {data: mutationData}) {
if (mutationData) {
const data: any = cache.readQuery({query: getArticlesQuery});
if (data) {
cache.writeQuery({
query: getArticlesQuery,
data: {
...data,
articles: data.articles.filter((article: any) => article.id !== mutationData.removeArticle),
},
});
}
}
},
});
return (
<>
{data?.articles && <div>{data.articles.map(({id, title}: any) => (
<div key={id}>
<Link to={`/${id}`}>{title}</Link>
<button onClick={() => removeArticle({optimisticResponse: {removeArticle: id}, variables: {id}}).catch(e => console.error(e.message))}>
Remove
</button>
</div>
))}</div>}
</>
);
}
export default Articles;