Created
November 7, 2021 22:45
-
-
Save llamadeus/ff8ffe7ac156e545575dad81142f1b6f to your computer and use it in GitHub Desktop.
Use React.Suspense for Apollo Client React hooks
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
import { gql, useQuery } from '@apollo/client'; | |
import React, { ReactElement, useEffect, useMemo, useRef } from 'react'; | |
const ME_QUERY = gql` | |
query Me { | |
me { | |
firstName | |
} | |
} | |
`; | |
function App() { | |
return ( | |
<React.Suspense fallback={<p>loading...</p>}> | |
<Dashboard/> | |
</React.Suspense> | |
); | |
} | |
function Dashboard() { | |
const { data, loading } = useQuery(ME_QUERY); | |
if (loading) { | |
return <Suspender/>; | |
} | |
return ( | |
<div> | |
<h1>Hello {data?.me?.firstName}</h1> | |
</div> | |
); | |
} | |
function Suspender(): ReactElement { | |
const resolve = useRef<() => void>(); | |
const promise = useMemo(() => new Promise<void>((res) => { | |
resolve.current = res; | |
}), []); | |
useEffect(() => { | |
return () => { | |
resolve.current?.(); | |
}; | |
}); | |
throw promise; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In React v18 they cancel all effects if the tree is suspended, and Apollo triggers the query through effect. Following implementation of
Suspender
worked out for us: