不变违规:在 nextjs 13 上使用 graphql 突变时

问题描述 投票:0回答:1

除了我的 graphql 突变之外,我的所有查询都运行良好。希望你能帮忙。

我在其他项目中使用相同的代码,唯一的区别是此表单位于模态内部。

error on showing

我知道我的操场上的这种突变正在发挥作用

graphql playground working mutation

这是我的完整注册文件

"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" },
    }),
  });
});


解决bug,并继续提交表单

reactjs graphql apollo next.js13
1个回答
0
投票

解决了

我不必在变量 {} 中传递对象

而不是

const response = await registerUser({
        variables: {
          input: {
            username: data.username,
            email: data.email,
            password: data.password,
          },
        },
      });

应该是

const response = await registerUser({
        variables: {
          username: data.username,
          email: data.email,
          password: data.password,
        },
      });

变异

export const CREATE_USER_MUTATION = gql`
  mutation register(
    $username: String!,
    $password: String!,
    $email: String!,
  ) {
    register(
      input: {
        username: $username,
        password: $password,
        email: $email,
      }
    ) {
      jwt
      user {
        id
        username
        email
        confirmed
        role {
          id
        }
      }
    }
  }
`;

和“使用客户端”;在js文件的顶部

© www.soinside.com 2019 - 2024. All rights reserved.