最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

redux toolkit - How can I call a Next.js server action from RTK Query endpoints without using an API route? - Stack Overflow

programmeradmin0浏览0评论

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.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论