Skip to content

Instantly share code, notes, and snippets.

@andyrichardson
Created April 8, 2020 13:34
Show Gist options
  • Save andyrichardson/d763368e03f08da199daccfb7692dc4b to your computer and use it in GitHub Desktop.
Save andyrichardson/d763368e03f08da199daccfb7692dc4b to your computer and use it in GitHub Desktop.
Quick and dirty Urql Suspense example
const useQuery = (query, opts) => {
const source = useRef();
const [state, setState] = useState();
const makeRead = useCallback(() => {
let status = "pending";
let response;
let promise = new Promise((resolve) => {
source.current = pipe(
client.createOperation(query, opts),
subscribe(
(data) => {
setState({ fetching: false, data })
response = { fetching: false, data };
status = "success";
resolve(response);
}, (error) => {
setState({ fetching: false, error }),
response = { fetching: false, error };
status = "success";
resolve(response)
})
)
}, [query, variables]);
return {
read: () => {
if (status === "pending") {
throw promise;
}
return response;
}
};
}, []);
return useMemo(() => {
if (state === undefined) {
return makeRead():
}
return { read: () => state };
}, [state]);
}
const MyApp = () => (
<Suspense fallback={<p>Fallback</p>}>
<MyPage />
</Suspense>
);
const MyPage = () => {
const users = useQuery();
const { data, error, fetching } = users.read();
if (fetching && !data) {
return <p>fetching</p>;
}
if (error) {
return <p>error</p>;
}
return <p>data</p>
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment