![](/img/trans.png)
[英]How to generate Graphql types for React with help of graphql-codegen when Apollo Server is in production mode?
[英]Using getServerSideProps for graphql-codegen mutation in nextjs
我想在getServerSideProps
中执行 graphql 突变。 我正在使用 graphql-codegen 从我的 graphql 调用中生成代码。 我用来执行突变的代码是:
const [getTokenMutation, _] = useGetTokenMutation()
const token = await getTokenMutation({
当我将工作代码从函数体移动到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 ...
为了解决这个问题,我查看了 graphql-codegen 的graphql-codegen-apollo-next-ssr
插件。 不幸的是,这只是为我定义的查询生成代码,而不是为突变生成代码。
如何从 getServerSideProps 执行我的突变?
服务器端函数是 Node - 而不是 React,所以你不能在这些函数中使用 React 钩子。
您需要在每个函数中调用 Apollo 客户端查询/突变。 Next.js 有多个 Apollo 示例 - 这是一个.
阿波罗客户端.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: {} });
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.