Is it okay to call a server action directly from a useQuery or a useMutation hook? (with example)

I know that in app router you can directly call the server function, but if I have a interactive client component, is it okay to call the server action from a useQuery or useMutation hook? Because this is not one of the ways they speak about in the documentation: https://nextjs.org/docs/app/api-reference/functions/server-actions#invocation
// actions.ts

"use server";

export const getPosts = async () => {
// fetch from db
const posts = [{ id: 1, name: "Hello World" }];
return posts;
};
// actions.ts

"use server";

export const getPosts = async () => {
// fetch from db
const posts = [{ id: 1, name: "Hello World" }];
return posts;
};
// page.tsx

"use client";

import { useQuery } from "@tanstack/react-query";
import { getPosts } from "./actions";

export default function Home() {
const { data, error, isLoading } = useQuery({
queryKey: ["posts"],
queryFn: getPosts,
});

return error ? (
<div>Oops, an error</div>
) : isLoading ? (
<div>Loading...</div>
) : (
<ul>
{data.map((post) => (
<li key={post.id}>{post.name}</li>
))}
</ul>
);
}
// page.tsx

"use client";

import { useQuery } from "@tanstack/react-query";
import { getPosts } from "./actions";

export default function Home() {
const { data, error, isLoading } = useQuery({
queryKey: ["posts"],
queryFn: getPosts,
});

return error ? (
<div>Oops, an error</div>
) : isLoading ? (
<div>Loading...</div>
) : (
<ul>
{data.map((post) => (
<li key={post.id}>{post.name}</li>
))}
</ul>
);
}
0 Replies
No replies yetBe the first to reply to this messageJoin
Want results from more Discord servers?
Add your server