T
TanStack16mo ago
like-gold

Calling server action using useQuery?

'use client';
import { useQuery } from '@tanstack/react-query';

export const runtime = 'edge';

export async function getCustomer(userId: string): Promise<any> {
"use server";
const customerInfo = (
await db
.select()
.from(customerTable)
.where(eq(customerTable.userId, userId))
)[0];

return Response.json(customerInfo);
}

export default function Page({ params }: { params: { userId: string } }) {
const { data } = useQuery({
queryKey: ['publicCustomer', userId],
queryFn: async () => {
const response = await getCustomer(params.userId);
const data = await response.json();
return data;
},
});

return (
<div>{data}</div>
);
}
'use client';
import { useQuery } from '@tanstack/react-query';

export const runtime = 'edge';

export async function getCustomer(userId: string): Promise<any> {
"use server";
const customerInfo = (
await db
.select()
.from(customerTable)
.where(eq(customerTable.userId, userId))
)[0];

return Response.json(customerInfo);
}

export default function Page({ params }: { params: { userId: string } }) {
const { data } = useQuery({
queryKey: ['publicCustomer', userId],
queryFn: async () => {
const response = await getCustomer(params.userId);
const data = await response.json();
return data;
},
});

return (
<div>{data}</div>
);
}
When I open the page in my browser, then I get this error in the server logs:
⨯ Internal error: Error: Only plain objects, and a few built-ins, can be passed to Client Components from Server Components. Classes or null prototypes are not supported.
⨯ Internal error: Error: Only plain objects, and a few built-ins, can be passed to Client Components from Server Components. Classes or null prototypes are not supported.
Is it possible to call a Nextjs Next.js server action using useQuery? - If so, how?
1 Reply
like-gold
like-goldOP16mo ago
Solved. Mistake #1:
return Response.json(customerInfo);
return Response.json(customerInfo);
should be
return customerInfo;
return customerInfo;
Mistake #2:
const response = await getCustomer(params.userId);
const data = await response.json();
return data;
const response = await getCustomer(params.userId);
const data = await response.json();
return data;
should be
const data = await getCustomer(params.userId);
return data;
const data = await getCustomer(params.userId);
return data;

Did you find this page helpful?