admin管理员组文章数量:1393563
I'm using Next.js with the new app router and server actions (i.e. files marked with "use server";) to encapsulate my server-side logic. For example, I have a server action defined like this:
"use server";
import fetchWithToken from "../_utils/fetchWithToken";
export async function getProjects() {
try {
const response = await fetchWithToken("https://localhost:7259/getProjects");
if (!response.ok) {
return { error: "Failed to fetch projects", status: response.status };
}
const data = await response.json();
return data;
} catch (error) {
console.error("Error in GET:", error);
return { error: "Internal server error", status: 500 };
}
}
I was able to call this server action from a Redux thunk like so:
export const fetchProjectsThunk = createAsyncThunk(
"project/fetchProjects",
async (_, { rejectWithValue }) => {
try {
const data = await getProjects();
if (data.error) {
throw new Error(data.error);
}
return data;
} catch (e) {
return rejectWithValue(e.message);
}
}
);
This thunk is dispatched from my client component and works because, under the hood, the thunk is handled in a way that allows calling server actions.
Now, I'm trying to use RTK Query instead, with a setup like this:
import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react";
import fetchWithToken from "../_utils/fetchWithToken";
const baseQueryWithAuth = fetchBaseQuery({
baseUrl: "https://localhost:7259/projects/",
fetchFn: fetchWithToken,
});
export const projectsApi = createApi({
reducerPath: "projectsApi",
baseQuery: baseQueryWithAuth,
endpoints: (builder) => ({
getProjects: builder.query({ query: () => "getAll" }),
createProject: builder.mutation({
query: (newProject) => ({
url: "create",
method: "POST",
body: newProject,
}),
}),
}),
});
export const { useGetProjectsQuery, useCreateProjectMutation } = projectsApi;
I want RTK Query to call my server action (getProjects) instead of directly hitting the endpoint via the base query. However, this doesn't work because server actions are only callable in a server context, and RTK Query runs on the client.
My question is: Is there a way to configure RTK Query to call a Next.js server action directly from a client component without having to expose an API route? If not, what is the recommended pattern to use RTK Query together with server actions in the Next.js app router context?
Any insights or workarounds would be greatly appreciated.
本文标签:
版权声明:本文标题:redux toolkit - How can I call a Next.js server action from RTK Query endpoints without using an API route? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744763993a2623922.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论