Invariant Violation: When using graphql Mutation on nextjs 13

Invariant Violation: When using graphql Mutation on nextjs 13


0

all my query is working well, except for my graphql mutation. hope you can help.

I’m using the same code on my other project, the only difference is this form is inside a modal.

error on showing

And I know this mutation on my playground is working

graphql playground working mutation

here’s my full registration file

"use client";
import React, { useContext } from "react";
import { gql, useMutation } from "@apollo/client";
import { useForm, SubmitHandler } from "react-hook-form";
import Modal from "../Modal/Modal";
import { ModalContext } from "@/app/contex/modal";

// Define the GraphQL mutation
const REGISTER_USER_MUTATION = gql`
  mutation RegisterUser($input: RegisterInput!) {
    register(input: $input) {
      jwt
      user {
        id
        username
        email
        confirmed
        role {
          id
        }
      }
    }
  }
`;

interface RegistrationFormData {
  username: string;
  email: string;
  password: string;
}

const Register: React.FC = () => {
  const modalContext = useContext(ModalContext);

  // Ensure that modalContext is not undefined before using its properties
  if (!modalContext) {
    throw new Error("ModalContext not available");
  }

  const { modalStatus, setModalStatus } = modalContext;
  const {
    register,
    handleSubmit,
    reset,
    formState: { errors },
    watch,
  } = useForm<RegistrationFormData>();

  // Define the useMutation hook with types
  const [registerUser, { loading, error, data }] = useMutation<{
    register: { jwt: string; user: User };
  }>(REGISTER_USER_MUTATION);

  const onSubmit: SubmitHandler<RegistrationFormData> = async (data) => {
    try {
      const response = await registerUser({
        variables: {
          input: {
            username: data.username,
            email: data.email,
            password: data.password,
          },
        },
      });

      if (response.errors) {
        // Handle GraphQL errors here, e.g., display error messages
        console.error("GraphQL errors:", response.errors);
        return;
      }

      // Handle successful registration
      console.log("User registration response:", response.data);

      // Reset the form after successful registration
      reset();
    } catch (err) {
      // Handle registration error, e.g., display an error message
      console.error("Registration error:", err);
    }
  };

  const password = watch("password");

  return (
    <Modal>
      <h1>Register</h1>
      <form onSubmit={handleSubmit(onSubmit)}>
        {/* Form fields and validation errors remain the same */}
        <div>
          <label htmlFor="username">Username</label>
          <input
            type="text"
            id="username"
            {...register("username", { required: "Username is required" })}
          />
          {errors.username && <span>{errors.username.message}</span>}
        </div>
        <div>
          <label htmlFor="email">Email</label>
          <input
            type="email"
            id="email"
            {...register("email", { required: "Email is required" })}
          />
          {errors.email && <span>{errors.email.message}</span>}
        </div>
        <div>
          <label htmlFor="password">Password</label>
          <input
            type="password"
            id="password"
            {...register("password", { required: "Password is required" })}
          />
          {errors.password && <span>{errors.password.message}</span>}
        </div>
        <div>
          <label htmlFor="confirmPassword">Confirm Password</label>
          <input
            type="password"
            id="confirmPassword"
            {...register("confirmPassword", {
              required: "Please confirm your password",
              validate: (value) =>
                value === password || "Passwords do not match",
            })}
          />
          {errors.confirmPassword && (
            <span>{errors.confirmPassword.message}</span>
          )}
        </div>
        <div>
          <button type="submit">Register</button>
        </div>
      </form>
      <button
        onClick={() => {
          setModalStatus(""); // Clear modal status
        }}
      >
        Close
      </button>
    </Modal>
  );
};

export default Register;

"lib/apollo-wrapper.js"

"use client";

import {
  ApolloClient,
  ApolloLink,
  HttpLink,
} from "@apollo/client";
import {
  ApolloNextAppProvider,
  NextSSRInMemoryCache,
  SSRMultipartLink, 
  NextSSRApolloClient
} from "@apollo/experimental-nextjs-app-support/ssr";

function makeClient() {
  const httpLink = new HttpLink({
      // https://studio.apollographql.com/public/spacex-l4uc6p/
      uri: process.env.NEXT_PUBLIC_API_ENDPOINT,
  });

  return new NextSSRApolloClient({
    cache: new NextSSRInMemoryCache(),
    link:
      typeof window === "undefined"
        ? ApolloLink.from([
            new SSRMultipartLink({
              stripDefer: true,
            }),
            httpLink,
          ])
        : httpLink,
  });
}

export function ApolloWrapper({ children }) {
  return (
    <ApolloNextAppProvider makeClient={makeClient}>
      {children}
    </ApolloNextAppProvider>
  );
}

"lib/client.js"

import { ApolloClient, HttpLink, InMemoryCache } from "@apollo/client";
import {
  NextSSRInMemoryCache,
  NextSSRApolloClient,
} from "@apollo/experimental-nextjs-app-support/ssr";
import { registerApolloClient } from "@apollo/experimental-nextjs-app-support/rsc";

export const { getClient } = registerApolloClient(() => {
  return new NextSSRApolloClient({
    cache: new NextSSRInMemoryCache(),
    link: new HttpLink({
      // https://studio.apollographql.com/public/spacex-l4uc6p/
      uri: process.env.NEXT_PUBLIC_API_ENDPOINT,
      // you can disable result caching here if you want to
      // (this does not work if you are rendering your page with `export const dynamic = "force-static"`)
      // fetchOptions: { cache: "no-store" },
    }),
  });
});


To resolve the bug, and continue with the form submission

New contributor

Gilbert Lucas is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.


Load 5 more related questions


Show fewer related questions

0



Leave a Reply

Your email address will not be published. Required fields are marked *