Skip to content

Added useFlowQueryRaw hook #2523

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Jun 19, 2025
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .changeset/wicked-bikes-peel.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
"@onflow/fcl-core": minor
"@onflow/fcl": minor
"@onflow/kit": minor
---

Added useFlowQueryRaw hook to execute a query and get non-decoded data as result.
48 changes: 0 additions & 48 deletions packages/fcl-core/src/exec/query.js

This file was deleted.

34 changes: 34 additions & 0 deletions packages/fcl-core/src/exec/query.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import * as sdk from "@onflow/sdk"
import {QueryOptions, rawQuery} from "./raw-query"

/**
* @description Allows you to submit scripts to query the blockchain.
*
* @param opts Query Options and configuration
* @param opts.cadence Cadence Script used to query Flow
* @param opts.args Arguments passed to cadence script
* @param opts.template Interaction Template for a script
* @param opts.isSealed Block Finality
* @param opts.limit Compute Limit for Query
* @returns A promise that resolves to the query result
*
* @example
* const cadence = `
* cadence: `
* access(all) fun main(a: Int, b: Int, c: Address): Int {
* log(c)
* return a + b
* }
* `.trim()
*
* const args = (arg, t) => [
* arg(5, t.Int),
* arg(7, t.Int),
* arg("0xb2db43ad6bc345fec9", t.Address),
* ]
*
* await query({ cadence, args })
*/
export async function query(opts: QueryOptions = {}): Promise<any> {
return rawQuery(opts).then(sdk.decode)
}
55 changes: 55 additions & 0 deletions packages/fcl-core/src/exec/raw-query.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import * as sdk from "@onflow/sdk"
import type {ArgsFn} from "./args"
import {normalizeArgs} from "./utils/normalize-args"
import {preQuery} from "./utils/pre"
import {prepTemplateOpts} from "./utils/prep-template-opts"

export interface QueryOptions {
cadence?: string
args?: ArgsFn
template?: any
isSealed?: boolean
limit?: number
}

/**
* @description Allows you to submit scripts to query the blockchain and get raw response data.
*
* @param opts Query Options and configuration
* @param opts.cadence Cadence Script used to query Flow
* @param opts.args Arguments passed to cadence script
* @param opts.template Interaction Template for a script
* @param opts.isSealed Block Finality
* @param opts.limit Compute Limit for Query
* @returns A promise that resolves to the raw query result
*
* @example
* const cadence = `
* cadence: `
* access(all) fun main(a: Int, b: Int, c: Address): Int {
* log(c)
* return a + b
* }
* `.trim()
*
* const args = (arg, t) => [
* arg(5, t.Int),
* arg(7, t.Int),
* arg("0xb2db43ad6bc345fec9", t.Address),
* ]
*
* await rawQuery({ cadence, args })
*/
export async function rawQuery(opts: QueryOptions = {}): Promise<any> {
await preQuery(opts)
opts = await prepTemplateOpts(opts)

return sdk.send([
sdk.script(opts.cadence!),
sdk.args(normalizeArgs(opts.args || [])),
sdk.atLatestBlock(opts.isSealed ?? false),
opts.limit &&
typeof opts.limit === "number" &&
(sdk.limit(opts.limit!) as any),
])
}
1 change: 1 addition & 0 deletions packages/fcl-core/src/fcl-core.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
export {VERSION} from "./VERSION"
export {query} from "./exec/query"
export {rawQuery} from "./exec/raw-query"
export {verifyUserSignatures} from "./exec/verify"
export {serialize} from "./serialize"
export {transaction as tx, TransactionError} from "./transaction"
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import {config, invariant} from "@onflow/sdk"
import {log, LEVELS} from "@onflow/util-logger"
import {query} from "../exec/query.js"
import {query} from "../exec/query"
import {generateTemplateId} from "./generate-template-id/generate-template-id.js"
import {getChainId} from "../utils"

Expand Down
1 change: 1 addition & 0 deletions packages/fcl/src/fcl.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
export {
VERSION,
query,
rawQuery,
verifyUserSignatures,
serialize,
tx,
Expand Down
1 change: 1 addition & 0 deletions packages/kit/src/__mocks__/fcl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ export default {
events: jest.fn(),
mutate: jest.fn(),
query: jest.fn(),
rawQuery: jest.fn(),
tx: jest.fn(),
config: () => ({
subscribe: sharedSubscribe,
Expand Down
1 change: 1 addition & 0 deletions packages/kit/src/hooks/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ export {useFlowConfig} from "./useFlowConfig"
export {useFlowEvents} from "./useFlowEvents"
export {useFlowMutate} from "./useFlowMutate"
export {useFlowQuery} from "./useFlowQuery"
export {useFlowQueryRaw} from "./useFlowQueryRaw"
export {useFlowRevertibleRandom} from "./useFlowRevertibleRandom"
export {useCrossVmBatchTransaction} from "./useCrossVmBatchTransaction"
export {useCrossVmTokenBalance} from "./useCrossVmTokenBalance"
Expand Down
186 changes: 186 additions & 0 deletions packages/kit/src/hooks/useFlowQueryRaw.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,186 @@
import {renderHook, act, waitFor} from "@testing-library/react"
import * as fcl from "@onflow/fcl"
import {FlowProvider} from "../provider"
import {useFlowQueryRaw} from "./useFlowQueryRaw"

jest.mock("@onflow/fcl", () => require("../__mocks__/fcl").default)

describe("useFlowQueryRaw", () => {
afterEach(() => {
jest.clearAllMocks()
})

test("returns undefined when no cadence is provided", async () => {
const {result} = renderHook(() => useFlowQueryRaw({cadence: ""}), {
wrapper: FlowProvider,
})

expect(result.current.data).toBeUndefined()
await waitFor(() => expect(result.current.isLoading).toBe(false))
})

test("fetches data successfully", async () => {
const cadenceScript = "access(all) fun main(): Int { return 42 }"
const expectedResult = 42
const queryMock = jest.mocked(fcl.rawQuery)
queryMock.mockResolvedValueOnce(expectedResult)

let hookResult: any

await act(async () => {
const {result} = renderHook(
() => useFlowQueryRaw({cadence: cadenceScript}),
{
wrapper: FlowProvider,
}
)
hookResult = result
})

expect(hookResult.current.data).toBeUndefined()

await waitFor(() => expect(hookResult.current.isLoading).toBe(false))
expect(hookResult.current.data).toEqual(expectedResult)
expect(queryMock).toHaveBeenCalledWith({
cadence: cadenceScript,
args: undefined,
})
})

test("does not fetch data when enabled is false", async () => {
const cadenceScript = "access(all) fun main(): Int { return 42 }"
const queryMock = jest.mocked(fcl.rawQuery)

renderHook(
() => useFlowQueryRaw({cadence: cadenceScript, query: {enabled: false}}),
{
wrapper: FlowProvider,
}
)

// wait a little to ensure fcl.rawQuery isn't called
await waitFor(() => {
expect(queryMock).not.toHaveBeenCalled()
})
})

test("handles error from fcl.rawQuery", async () => {
const cadenceScript = "access(all) fun main(): Int { return 42 }"
const testError = new Error("Query failed")
const queryMock = jest.mocked(fcl.rawQuery)
queryMock.mockRejectedValueOnce(testError)

let hookResult: any

await act(async () => {
const {result} = renderHook(
() => useFlowQueryRaw({cadence: cadenceScript}),
{
wrapper: FlowProvider,
}
)
hookResult = result
})

await waitFor(() => expect(hookResult.current.isLoading).toBe(false))
expect(hookResult.current.data).toBeUndefined()
expect(hookResult.current.error).toEqual(testError)
})

test("refetch function works correctly", async () => {
const cadenceScript = "access(all) fun main(): Int { return 42 }"
const initialResult = 42
const updatedResult = 100
const queryMock = jest.mocked(fcl.rawQuery)
queryMock.mockResolvedValueOnce(initialResult)

let hookResult: any

await act(async () => {
const {result} = renderHook(
() => useFlowQueryRaw({cadence: cadenceScript}),
{
wrapper: FlowProvider,
}
)
hookResult = result
})

await waitFor(() => expect(hookResult.current.data).toEqual(initialResult))

queryMock.mockResolvedValueOnce(updatedResult)
act(() => {
hookResult.current.refetch()
})

await waitFor(() => expect(hookResult.current.data).toEqual(updatedResult))
expect(queryMock).toHaveBeenCalledTimes(2)
})

test("supports args function parameter", async () => {
const cadenceScript = "access(all) fun main(a: Int): Int { return a }"
const expectedResult = 7
const queryMock = jest.mocked(fcl.rawQuery)
queryMock.mockResolvedValueOnce(expectedResult)

const argsFunction = (arg: typeof fcl.arg, t: typeof fcl.t) => [
arg(7, t.Int),
]

let hookResult: any

await act(async () => {
const {result} = renderHook(
() => useFlowQueryRaw({cadence: cadenceScript, args: argsFunction}),
{
wrapper: FlowProvider,
}
)
hookResult = result
})

await waitFor(() => expect(hookResult.current.isLoading).toBe(false))
expect(hookResult.current.data).toEqual(expectedResult)
expect(queryMock).toHaveBeenCalledWith({
cadence: cadenceScript,
args: argsFunction,
})
})

test("detects args changes", async () => {
const cadenceScript = "access(all) fun main(a: Int): Int { return a }"
const initialResult = 7
const updatedResult = 42
const queryMock = jest.mocked(fcl.rawQuery)
queryMock.mockResolvedValueOnce(initialResult)

const argsFunction = (arg: typeof fcl.arg, t: typeof fcl.t) => [
arg(7, t.Int),
]

let hookResult: any
let hookRerender: any

await act(async () => {
const {result, rerender} = renderHook(useFlowQueryRaw, {
wrapper: FlowProvider,
initialProps: {cadence: cadenceScript, args: argsFunction},
})
hookResult = result
hookRerender = rerender
})

await waitFor(() => expect(hookResult.current.isLoading).toBe(false))
expect(hookResult.current.data).toEqual(initialResult)

queryMock.mockResolvedValueOnce(updatedResult)
await act(() => {
hookRerender({
cadence: cadenceScript,
args: (arg: typeof fcl.arg, t: typeof fcl.t) => [arg(42, t.Int)],
})
})

await waitFor(() => expect(hookResult.current.data).toEqual(updatedResult))
})
})
Loading