在 Next.js 中将服务器组件包装在客户端中

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

我有一个使用 graphql 和 apolloq 将数据添加到 json 的表单。我正在使用 typescript 和 next.js 采取行动。获取有关服务器客户端组件的冲突错误。 在表单组件中使用hook,因此使用“使用客户端”。但是,当从 page.tsx 引用时,出现错误 未处理的运行时错误 违反不变性:发生错误!

export const ADD_USER = gql`
  mutation AddUser($name: String!, $email: String!) {
    createUser(name: $name, email: $email) {
      id
      name
      email
    }
  }
`;


  const UserForm: React.FC = () => {
    const [name, setName] = useState('');
    const [email, setEmail] = useState('');
  
    const [addUserMutation] = useMutation(ADD_USER);
  
    const handleSubmit = async (e: FormEvent<HTMLFormElement>) => {
      e.preventDefault();
      try {
        await addUserMutation({
          variables: {
            input: {
              name,
              email,
            },
          },
        });
        // Optionally, clear the form fields
        setName('');
        setEmail('');
        console.log('User added successfully!');
      } catch (error) {
        console.error('Error adding user:', error);
      }
    };

  return (
    <form  className='userform' onSubmit={handleSubmit} >
     
      <FormControl fullWidth margin="normal">
        <InputLabel  htmlFor="firstName">First Name</InputLabel >
        <TextField
          className='name'
          name='name'
          value={name}
          type='text'
          onChange={(e) => setName(e.target.value)}
         
        /> 
      </FormControl >
       <FormControl fullWidth margin="normal">
      <InputLabel htmlFor="phone">Phone</InputLabel>
        <TextField
          className='email'
          name='email'
          value={email}
          type='text'
          onChange={(e) => setEmail(e.target.value)}
          
        /> 
      </FormControl>
      <FormGroup > 
        <Button variant="contained" type="submit">Add        
        </Button>
      </FormGroup>
    </form>
  );
};

export default UserForm;
reactjs typescript next.js graphql apollo
1个回答
0
投票

我已经解决了。添加了 apollowrapper 并用它包装了layout.ts。

阿波罗包装器

//src/lib/apollo-wrapper.ts
"use client";

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

function makeClient() {
  const httpLink = new HttpLink({
      uri: "http://localhost:3000/api/graphql",
  });

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

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

布局.ts

   <ApolloWrapper>
      {children}    
      </ApolloWrapper> 
© www.soinside.com 2019 - 2024. All rights reserved.