在nextjs中使用getserversideprops进行graphql-codegen突变

发布于 2025-02-09 12:17:11 字数 489 浏览 1 评论 0原文

我想在getServersideProps中执行GraphQl突变。我正在使用GraphQL-Codegen从我的GraphQl调用中生成代码。我用来执行突变的代码是:

const [getTokenMutation, _] = useGetTokenMutation()
const token = await getTokenMutation({

当我将工作代码从函数主体移动到getserversideprops时,我会得到错误:错误:无效挂钩调用。钩子只能在功能组件的主体内部调用。这可能是出于以下原因之一...

解决此问题,我将其视为graphql-codegen-apollo-next-ssr graphql-codegen的插件。不幸的是,这仅是为我定义的查询而不是为突变生成代码。

如何从GetServersideProps中执行突变?

I would like to perform a graphql mutation in getServerSideProps. I am using graphql-codegen to generate code from my graphql call. The code I use to perform my mutation is:

const [getTokenMutation, _] = useGetTokenMutation()
const token = await getTokenMutation({

When I move the working code from the function body to getServerSideProps I get the error: Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons ...

To solve this I looked in to the graphql-codegen-apollo-next-ssr plugin for graphql-codegen. Unfortunately this only is generating code for the queries I have defined, not for the mutations.

How can I perform my mutation from getServerSideProps?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

岁月流歌 2025-02-16 12:17:11

服务器端功能是节点 - 不反应,因此您不能在这些功能中使用React Hook。

您需要在每个功能中调用Apollo客户端查询/突变。 next.js有多个阿波罗示例 - 这是一个


apollo-client.js

import { ApolloClient, InMemoryCache } from "@apollo/client";

export const client = new ApolloClient({
    uri: "https://example.com/graphql",
    cache: new InMemoryCache(),
    ...YOUR_SETTINGS
});

somepage.js

import { gql } from "@apollo/client";
import { client } from "./apollo-client";

export async function getServerSideProps() {
    // query
    const { data } = await client.query({query: gql`query SomeQuery {...}`});
    // mutation
    const { data } = await client.mutate({ mutation: gql`mutation getToken {...}`, variables: {} });

}

The server-side function are Node - not React, so you can't use React hooks in those functions.

You need to call the Apollo client query/mutation in each function. Next.js has multiple Apollo examples - here is one.


apollo-client.js

import { ApolloClient, InMemoryCache } from "@apollo/client";

export const client = new ApolloClient({
    uri: "https://example.com/graphql",
    cache: new InMemoryCache(),
    ...YOUR_SETTINGS
});

SomePage.js

import { gql } from "@apollo/client";
import { client } from "./apollo-client";

export async function getServerSideProps() {
    // query
    const { data } = await client.query({query: gql`query SomeQuery {...}`});
    // mutation
    const { data } = await client.mutate({ mutation: gql`mutation getToken {...}`, variables: {} });

}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文