queryFn with server action name not working on Next.js #7330
Send to my agentDescribe the bug#
I'm using useQuery hook with my Next.js 14.1.3 project. I'd like to use server action as query function, so I made my codes like this.
actions/fetchTasks.ts
"use server"
const fetchTasks = async () => {
try {
const { data, errors } = client.graphql({ // I'm using AWS Amplify Graphql client
query: listTasks,
variables: {
filter: {},
},
});
if (errors) throw new Error(errors[0].message);
return data.listTasks.items as Task[];
} catch (err) {
console.log(err);
return [];
}
};
export default fetchTasks;
hooks/useTasks.ts
"use client"
import fetchTasks from "../actions/fetchTasks";
const useTasks = () => {
const { data } = useQuery({
queryKey: ["tasks"],
queryFn: fetchTasks, // using function name
});
return { data };
};
export default useTasks;
However, this didn't work. Data from useTasks hook always returned undefined.
When I put console.log at the top of inside fetchTasks function, this didn't show up, so I think using function name as queryFn is completely not working.
After some trials and errors, replacing function name with anonymous arrow function solved this problem.
hooks/useTasks.ts
"use client"
import fetchTasks from "../actions/fetchTasks";
const useTasks = () => {
const { data } = useQuery({
queryKey: ["tasks"],
queryFn: () => fetchTasks(), // using anonymous arrow function
});
return { data };
};
export default useTasks;
Is this expected behavior? I know many of documentation codes are using function name as queryFn. (e.g. https://tanstack.com/query/latest/docs/framework/react/quick-start)
Your minimal, reproducible example#
https://codesandbox.io/p/github/tsuyuni/ReproduceQueryFnWithFunctionNameNotWorking/main?import=true
Steps to reproduce#
Just run npm i and npm run dev.
Then you will see: Tasks with function name has no tasks though expected to have 3 tasks. Tasks with anonymous arrow function has 3 tasks as it was expected.
Expected behavior#
queryFn with function name should properly work.
How often does this bug happen?#
Every time
Screenshots or Videos#
No response
Platform#
OS: Sonoma 14.2
Tanstack Query adapter#
react-query
TanStack Query version#
5.32.0
TypeScript version#
5.4.5
Additional context#
No response
TkDodo closed this
TkDodo added labelsduplicate
Yes, took me 5 hours to find the workaround. Drove me crazy.
Sign in to join this conversation.
feel free to update this in the docs somewhere because it keeps coming up: