Created
November 3, 2022 19:24
-
-
Save JFrankfurt/21b68af1e7e9f3683ed18ce4cf71c9b6 to your computer and use it in GitHub Desktop.
dumb relay data fetching hook
This file contains hidden or 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 { fetchQuery, useRelayEnvironment } from 'react-relay' | |
import { useEffect, useState } from 'react' | |
interface ArgsInterface { | |
numResults: number | |
pollingInterval: number | |
} | |
export function useSomeRelayQuery({ numResults, pollingInterval }: ArgsInterface): { | |
data: SomeTypeQuery$data | null | |
loading: boolean | |
error: Error | null | |
} { | |
const [data, setData] = useState<SomeTypeQuery$data | null>(null) | |
const [loading, setLoading] = useState(false) | |
const [error, setError] = useState<Error | null>(null) | |
const [reload, setReload] = useState(false) | |
useEffect(() => { | |
const interval = setInterval(() => setReload(true), pollingInterval) | |
return () => clearInterval(interval) | |
}) | |
const environment = useRelayEnvironment() | |
useEffect(() => { | |
if (!reload) { | |
return | |
} | |
const subscription = fetchQuery<SomeTypeQuery>(environment, query, { numResults }).subscribe({ | |
start() { | |
setReload(false) | |
setError(null) | |
setLoading(true) | |
}, | |
next(newData) { | |
setData(newData) | |
}, | |
error(e: Error) { | |
setError(e) | |
}, | |
complete() { | |
setLoading(false) | |
}, | |
}) | |
return () => subscription.unsubscribe() | |
}, [environment, numResults, reload]) | |
return { data, error, loading } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment