Created
July 16, 2020 09:35
-
-
Save mtsmfm/366f3d68bf9c2ee0e3a2db8a6403245a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const postQuery = async <TData, TVariables>(query: string, variables: TVariables) => { | |
const token = await firebase.auth().currentUser!.getIdToken(); | |
const resonse = await fetch('/graphql', { | |
method: 'POST', | |
credentials: 'include', | |
headers: { | |
'content-type': 'application/json', | |
'authorization': `Bearer ${token}`, | |
'X-CSRF-Token': document.querySelector('meta[name="csrf-token"]')!.getAttribute('content')! | |
}, | |
body: JSON.stringify({ query, variables }) | |
}); | |
const json: { data: TData, errors: Array<any> | undefined } = await resonse.json(); | |
return json; | |
} | |
const useLazyQuery = <TData, TVariables>(query: DocumentNode) => { | |
const [state, setState] = useState<QueryState<TData>>({ loading: false, error: false, data: undefined }); | |
const isMountedRef = useIsMountedRef(); | |
const func = async (variables: TVariables) => { | |
setState({ loading: true, error: false, data: undefined }); | |
try { | |
const { data, errors } = await postQuery<TData, TVariables>(print(query), variables); | |
if (isMountedRef.current) { | |
setState({ loading: false, error: !!errors, data }); | |
} | |
} catch { | |
setState({ loading: false, error: true, data: undefined }); | |
} | |
} | |
return [func, state] as const; | |
} | |
const [fetch, { data, loading, error }] = useLazyQuery<AppQuery, AppQueryVariables>(gql` | |
query App { | |
gcpInstances { | |
...GcpInstances_GcpInstance | |
} | |
parsecHosts { | |
...ParsecHosts_ParsecHosts | |
} | |
} | |
${GcpInstances.Fragments.gcpInstances} | |
${ParsecHosts.Fragments.parsecHosts} | |
`); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment