This repository has been archived by the owner on Dec 2, 2021. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathApollo.tsx
65 lines (60 loc) · 1.93 KB
/
Apollo.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
55
56
57
58
59
60
61
62
63
64
65
import React, { useCallback } from 'react';
import { useDispatch } from 'react-redux';
import { useLocation } from 'react-router-dom';
import { useQuery, useMutation } from 'react-apollo';
import { gql } from 'apollo-boost';
import { loadApolloPage } from '../../../actions/pages';
import { Head } from '../../Head';
import { CodeSamplesBox } from '../../CodeSamplesBox';
import { Samples } from '../../../../server/responseSchema';
export const GET_SAMPLES = gql`
query getSamples($maxLength: Int) {
samples(maxLength: $maxLength) {
id
name
code
likeCount
description
}
}
`;
export const ADD_LIKE = gql`
mutation addLike($id: Int) {
addLike(id: $id) {
id
}
}
`;
export const Apollo = () => {
const dispatch = useDispatch();
const { search } = useLocation();
const maxLength = new URLSearchParams(search).get('max');
const { loading: queryLoading, error: queryError, data: queryData } = useQuery<{
samples: Samples;
}>(GET_SAMPLES, { variables: { maxLength: Number(maxLength) } });
const [
addLike,
{ loading: mutationLoading, error: mutationError, data: mutationData },
] = useMutation(ADD_LIKE, {
// need to optimize this because it's better to avoid fetching all data
refetchQueries: [{ query: GET_SAMPLES, variables: { maxLength: Number(maxLength) } }],
});
const like = useCallback((id: number) => {
addLike({ variables: { id } });
// if you want to use a local state variable, you have to specify it to `[]` because React captures this function
}, []);
// stop saga on Node.js
if (!process.env.IS_BROWSER) {
dispatch(loadApolloPage());
}
return (
<>
<Head title="apollo-page" />
<p>query: get all samples</p>
<p>mutation: add a like count</p>
{queryLoading && <p>loading...</p>}
{queryError && <p>error...</p>}
{queryData && <CodeSamplesBox samples={queryData.samples} addLike={like} />}
</>
);
};