-
-
Save maraisr/0dae4e89433c9bc27fafcf945d036cee to your computer and use it in GitHub Desktop.
useLocalQuery hook to consume local data from a GraphQL Query
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
const useLocalQuery = <TQuery extends {response: any; variables: any}>( | |
environment: Environment, | |
query: any, | |
inVariables: TQuery['variables'] = {} | |
): TQuery['response'] | null => { | |
const variables = useDeepEqual(inVariables) | |
const [dataRef, setData] = useRefState<SelectorData | null>(null) | |
const disposablesRef = useRef<Disposable[]>([]) | |
useEffect(() => { | |
const {getRequest, createOperationDescriptor} = environment.unstable_internal | |
const request = getRequest(query) | |
const operation = createOperationDescriptor(request, variables) | |
const res = environment.lookup(operation.fragment, operation) | |
setData(res.data || null) | |
disposablesRef.current.push(environment.retain(operation.root)) | |
disposablesRef.current.push( | |
environment.subscribe(res, (newSnapshot) => { | |
setData(newSnapshot.data || null) | |
}) | |
) | |
const disposables = disposablesRef.current | |
return () => { | |
disposables.forEach((disposable) => disposable.dispose()) | |
} | |
}, [environment, setData, query, variables]) | |
return dataRef.current | |
} |
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
const data = useLocalQuery<SnackbarQuery>(query) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment