-
Notifications
You must be signed in to change notification settings - Fork 0
/
useAppState.js
42 lines (32 loc) · 1.07 KB
/
useAppState.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
import _ from "lodash"
import { useQuery, useApolloClient } from "@apollo/react-hooks"
export default function useAppState({ query, variables } = {}) {
if (_.isEmpty(query)) throw new Error("Missing query")
const { data } = useQuery(query, {
fetchPolicy: "cache-only",
...(variables ? { variables } : {})
})
const queryField = getQueryField(query)
const appState = _.get(data, queryField)
const setAppState = useWriteQuery({ query, variables })
return [appState, setAppState]
}
function useWriteQuery({ query, variables }) {
const client = useApolloClient()
const queryField = getQueryField(query)
return function writeQuery(data) {
client.writeQuery({
query,
...(variables ? { variables } : {}),
data: { [queryField]: data }
})
}
}
function getQueryField(query) {
const operation = _.get(query, "definitions").find(
q => q.operation === "query"
)
if (!operation) throw new Error("You should pass an query operation")
const queryField = _.get(operation, "selectionSet.selections.0.name.value")
return queryField
}