|
1 | 1 | import React from 'react'; |
2 | 2 | import ReactDOM from 'react-dom'; |
3 | | -import { ApolloProvider } from '@apollo/react-hooks'; |
4 | | -import ApolloClient, { InMemoryCache } from 'apollo-boost'; |
| 3 | +import { |
| 4 | + ApolloClient, |
| 5 | + ApolloProvider, |
| 6 | + createHttpLink, |
| 7 | + InMemoryCache |
| 8 | +} from '@apollo/client'; |
| 9 | +import { setContext } from 'apollo-link-context'; |
5 | 10 |
|
6 | 11 | // import global styles |
7 | 12 | import GlobalStyle from '/components/GlobalStyle'; |
8 | 13 | // import our routes |
9 | 14 | import Pages from '/pages'; |
10 | 15 |
|
| 16 | +// configure our API URI & cache |
11 | 17 | const uri = process.env.API_URI; |
| 18 | +const httpLink = createHttpLink({ uri }); |
12 | 19 | const cache = new InMemoryCache(); |
13 | 20 |
|
14 | | -// configure Apollo Client |
| 21 | +// return the headers to the context |
| 22 | +const authLink = setContext((_, { headers }) => { |
| 23 | + return { |
| 24 | + headers: { |
| 25 | + ...headers, |
| 26 | + authorization: localStorage.getItem('token') || '' |
| 27 | + } |
| 28 | + }; |
| 29 | +}); |
| 30 | + |
| 31 | +// create the Apollo client |
15 | 32 | const client = new ApolloClient({ |
| 33 | + link: authLink.concat(httpLink), |
16 | 34 | cache, |
17 | | - uri, |
18 | | - clientState: { |
19 | | - resolvers: {}, |
20 | | - connectToDevTools: true |
21 | | - }, |
22 | | - request: operation => { |
23 | | - operation.setContext({ |
24 | | - headers: { |
25 | | - authorization: localStorage.getItem('token') || '' |
26 | | - } |
27 | | - }); |
28 | | - } |
| 35 | + resolvers: {}, |
| 36 | + connectToDevTools: true |
29 | 37 | }); |
30 | 38 |
|
31 | | -const initialCache = new Object({ |
32 | | - data: { |
33 | | - isLoggedIn: !!localStorage.getItem('token') |
34 | | - } |
35 | | -}); |
| 39 | +// check for a local token |
| 40 | +const data = { |
| 41 | + isLoggedIn: !!localStorage.getItem('token') |
| 42 | +}; |
36 | 43 |
|
37 | 44 | // write the cache data on initial load |
38 | | -cache.writeData(initialCache); |
39 | | -// write the cache data after the stored cache is reset |
40 | | -client.onResetStore(() => cache.writeData(initialCache)); |
| 45 | +cache.writeData({ data }); |
| 46 | +// write the cache data after cache is reset |
| 47 | +client.onResetStore(() => cache.writeData({ data })); |
41 | 48 |
|
42 | 49 | const App = () => { |
43 | 50 | return ( |
|
0 commit comments