This repository has been archived by the owner on Nov 6, 2023. It is now read-only.
forked from danielkaldheim/hk-tibber-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TibberProvider.tsx
85 lines (72 loc) · 2.21 KB
/
TibberProvider.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import React, { useContext, useMemo, useState, useEffect } from 'react';
import { AsyncStorage } from 'react-native';
import { ApolloClient } from 'apollo-client';
import { HttpLink } from 'apollo-link-http';
import { split } from 'apollo-link';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { WebSocketLink } from 'apollo-link-ws';
import { getMainDefinition } from 'apollo-utilities';
import { setContext } from 'apollo-link-context';
import { ApolloProvider } from '@apollo/react-hooks';
interface Props {
children: any;
}
const TibberContext = React.createContext({ accessToken: undefined });
export const TibberProvider = (props: Props) => {
const [accessToken, setAccessToken] = useState<string>('');
const httpLink = new HttpLink({ uri: `https://api.tibber.com/v1-beta/gql` });
const wsLink = new WebSocketLink({
uri: `wss://api.tibber.com/v1-beta/gql/subscriptions`,
options: {
reconnect: true,
connectionParams: {
token: `${accessToken}`,
},
},
});
const authLink = setContext((_, { headers }) => {
return {
headers: {
...headers,
authorization: `Bearer ${accessToken}`,
},
};
});
const link = split(
({ query }) => {
const definition = getMainDefinition(query);
return (
definition.kind === 'OperationDefinition' &&
definition.operation === 'subscription'
);
},
wsLink,
authLink.concat(httpLink)
);
const cache = new InMemoryCache();
const apolloClient = new ApolloClient({
cache,
link,
});
useEffect(() => {
AsyncStorage.getItem('tibber-access-token').then((data) => {
if (data) {
setAccessToken(JSON.parse(data));
}
});
}, []);
useEffect(() => {
AsyncStorage.setItem('tibber-access-token', JSON.stringify(accessToken));
}, [accessToken]);
const value = useMemo(() => {
return { accessToken, setAccessToken };
}, [accessToken]);
return (
<TibberContext.Provider value={value}>
<ApolloProvider client={apolloClient}>{props.children}</ApolloProvider>
</TibberContext.Provider>
);
};
const useTibber: any = () => useContext(TibberContext);
export { TibberContext, useTibber };
export default TibberProvider;