2

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?

sev
  • 1,500
  • 17
  • 45

1 Answers1

2

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

}
Sean W
  • 5,663
  • 18
  • 31
  • 1
    Would there be a way to still use graphql-codegen to generate a function that I can call from getServerSide props? Then I don't need to write out the query at every point in the code where I would like to use it... – sev Jun 22 '22 at 12:33
  • Another advantage of using graphql-codegen is that it gives me all the types – sev Jun 22 '22 at 13:14
  • It would be best if you wrote your queries & mutations; they are supposed to be specific per component/feature/etc., so you don't over/under fetch. I have a file for each database table with the queries I call, so I only have to write them in one place. I also use gql-codegen to assign types. – Sean W Jun 22 '22 at 14:48