Last active
July 16, 2020 09:38
-
-
Save mtsmfm/19d8585d06bde367717a343354c07f67 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', | |
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; | |
} | |
import { AppQuery, AppQueryVariables } from "../graphql-generated"; | |
export const App: React.FC = () => { | |
const [fetch, { data, loading, error }] = useLazyQuery<AppQuery, AppQueryVariables>(gql` | |
query App { | |
foo { | |
...Bar | |
} | |
} | |
${Bar.Fragments.Bar} | |
`); | |
useEffect(() => fetch(), []); | |
return <> | |
<Bar foo={data.foo} /> | |
</> | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment