简体   繁体   English

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

[英]Using getServerSideProps for graphql-codegen mutation in nextjs

I would like to perform a graphql mutation in getServerSideProps .我想在getServerSideProps中执行 graphql 突变。 I am using graphql-codegen to generate code from my graphql call.我正在使用 graphql-codegen 从我的 graphql 调用中生成代码。 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 ...当我将工作代码从函数体移动到getServerSideProps时,出现错误: 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 ... 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.为了解决这个问题,我查看了 graphql-codegen 的graphql-codegen-apollo-next-ssr插件。 Unfortunately this only is generating code for the queries I have defined, not for the mutations.不幸的是,这只是为我定义的查询生成代码,而不是为突变生成代码。

How can I perform my mutation from getServerSideProps?如何从 getServerSideProps 执行我的突变?

The server-side function are Node - not React, so you can't use React hooks in those functions.服务器端函数是 Node - 而不是 React,所以你不能在这些函数中使用 React 钩子。

You need to call the Apollo client query/mutation in each function.您需要在每个函数中调用 Apollo 客户端查询/突变。 Next.js has multiple Apollo examples - here is one . Next.js 有多个 Apollo 示例 - 这是一个.


apollo-client.js阿波罗客户端.js

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

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

SomePage.js 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: {} });

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM