Skip to content

Instantly share code, notes, and snippets.

@JFrankfurt
Created November 3, 2022 19:24
Show Gist options
  • Save JFrankfurt/21b68af1e7e9f3683ed18ce4cf71c9b6 to your computer and use it in GitHub Desktop.
Save JFrankfurt/21b68af1e7e9f3683ed18ce4cf71c9b6 to your computer and use it in GitHub Desktop.
dumb relay data fetching hook
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