I'm sending a request to a graphql endpoint using a useQuery hook, I work with react.js and next.js. This request is to show a list of projects on my website. When I check the network tab in the inspect tool in chrome browser, the request is ok, showing the response data without problem, but in the console, I got the next errors:
Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ["newProjects"]
Error: undefined at Object.onSuccess (query.mjs?b194:316:1) at resolve (retryer.mjs?bd96:54:1)
I created a hook to make the request and get the data in another component:
import { useQuery } from "@tanstack/react-query";
import { request, gql } from 'graphql-request'
import { endpointProjects } from "../settings";
export function useAllProjects() {
return useQuery(
['newProjects'],
async () => {
const data = await request(
endpointProjects.newProjects,
gql`
query MyQuery {
newProjects(orderBy: blockTimestamp, orderDirection: desc, first: 10, skip: 0) {
id
project
name
symbol
uri
blockNumber
blockTimestamp
transactionHash
}
}
`,
)
}
)
}
In another component, I just use the hook and show it in the console to see if I get the data:
const {data} = useAllProjects()
console.log('projects list: ', data)
CodePudding user response:
Your query function does not return anything, as you have those {}
and not a return
in them. You can give useQuery
an object with implicit keys like on the doc, and use an arrow function so your query function returns the result of request(...)
:
// imports
export function useAllProjects() {
return useQuery({
queryKey: ["newProjects"],
queryFn: async () =>
request(
endpointProjects.newProjects,
gql`
query MyQuery {
newProjects(orderBy: blockTimestamp, orderDirection: desc, first: 10, skip: 0) {
id
project
name
symbol
uri
blockNumber
blockTimestamp
transactionHash
}
}
`
),
});
}