Skip to content

Commit

Permalink
fix: Retain useClientQuery queries (#14873)
Browse files Browse the repository at this point in the history
* fix: Retain useClientQuery queries

* return disposable from hook
  • Loading branch information
olerichter00 authored Nov 21, 2024
1 parent 3036572 commit b574bd5
Showing 1 changed file with 22 additions and 3 deletions.
25 changes: 22 additions & 3 deletions src/Utils/Hooks/useClientQuery.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,18 @@
import { useUpdateEffect } from "@artsy/palette"
import { useEffect, useRef, useState } from "react"
import { Environment, fetchQuery, GraphQLTaggedNode } from "react-relay"
import {
Disposable,
Environment,
fetchQuery,
GraphQLTaggedNode,
} from "react-relay"
import {
CacheConfig,
createOperationDescriptor,
FetchQueryFetchPolicy,
getRequest,
OperationType,
} from "relay-runtime"
import { useUpdateEffect } from "@artsy/palette"
import { useSystemContext } from "System/Hooks/useSystemContext"

export const useClientQuery = <T extends OperationType>({
Expand All @@ -27,6 +34,7 @@ export const useClientQuery = <T extends OperationType>({
const { relayEnvironment } = useSystemContext()

const [data, setData] = useState<T["response"] | null>(null)
const [disposable, setDisposable] = useState<Disposable | null>(null)
const [error, setError] = useState<Error | null>(null)
const [loading, setLoading] = useState(true)

Expand All @@ -50,6 +58,16 @@ export const useClientQuery = <T extends OperationType>({

setData(res)
setLoading(false)

const operation = createOperationDescriptor(
getRequest(query),
variables ?? {}
)

// Retain the operation to prevent it from being garbage collected. Garbage collection can compromise type safety (e.g. non-nullable values being `null`), potentially leading to runtime errors.
const disposable = relayEnvironment.retain(operation)

setDisposable(disposable)
} catch (err) {
setError(err)
setLoading(false)
Expand All @@ -75,6 +93,7 @@ export const useClientQuery = <T extends OperationType>({
}, [
cacheConfig,
data,
disposable,
environment,
error,
query,
Expand All @@ -83,5 +102,5 @@ export const useClientQuery = <T extends OperationType>({
variables,
])

return { data, error, loading: skip ? false : loading, refetch }
return { data, disposable, error, loading: skip ? false : loading, refetch }
}

0 comments on commit b574bd5

Please sign in to comment.