This repository has been archived by the owner on Sep 23, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
100 lines (92 loc) · 2.52 KB
/
index.js
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
import React from "react";
import { render } from "react-dom";
import ApolloClient from "apollo-client";
import gql from "graphql-tag";
import { ApolloProvider, Subscription } from "react-apollo";
import { WebSocketLink } from "apollo-link-ws";
import { InMemoryCache } from "apollo-cache-inmemory";
import { BrowserRouter as Router, Route, Link } from "react-router-dom";
const client = new ApolloClient({
cache: new InMemoryCache({
addTypename: false
}),
link: new WebSocketLink({
uri: "ws://localhost:8080/v1/graphql",
options: {
reconnect: true
}
})
});
const App = () => (
<div>
<Router>
<Route path="/" exact component={Homepage} />
<Route path="/todo/:id" component={Todo} />
</Router>
</div>
);
const todoListSubscription = gql`
subscription todos {
todos {
pk
title
}
}
`;
function Homepage() {
return (
// passing any fetchPolicy here does the same, the inner component always renders twice
<Subscription fetchPolicy={"cache-only"} subscription={todoListSubscription}>
{({ loading, error, data }) => {
console.log("(todos) loading is", loading);
if (loading) return <div>Loading...</div>;
if (error) return <div>Error: {JSON.stringify(error, null, 4)}</div>;
return (
<ul>
{data.todos.map(todo => (
<li key={todo.pk}>
<Link to={`/todo/${todo.pk}`}>{todo.title}</Link>
</li>
))}
</ul>
);
}}
</Subscription>
);
}
const todoSubscription = gql`
subscription todo($pk: bigint) {
todos(where: { pk: { _eq: $pk } }) {
title
description
}
}
`;
function Todo({ match }) {
return (
// passing any fetchPolicy here does the same, the inner component always renders twice
<Subscription fetchPolicy={"cache-only"} subscription={todoSubscription} variables={{ pk: match.params.id }}>
{({ loading, error, data }) => {
console.log("(todo) loading is", loading);
if (loading) return <div>Loading...</div>;
if (error) return <div>Error: {JSON.stringify(error, null, 4)}</div>;
if (data.todos.length !== 1) return <div>not found</div>;
return (
<div>
<h1>{data.todos[0].title}</h1>
<p>{data.todos[0].description}</p>
</div>
);
}}
</Subscription>
);
}
render(
<ApolloProvider client={client}>
<App />
</ApolloProvider>,
document.getElementById("root")
);
if (module.hot) {
module.hot.accept();
}