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.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744763993a4592342.html
评论列表(0条)