在Apollo客户端中创建客户端端的突变,可以按照以下步骤进行:
import { ApolloClient, InMemoryCache, gql } from '@apollo/client';
const client = new ApolloClient({
uri: 'https://example.com/graphql', // 替换为实际的GraphQL API地址
cache: new InMemoryCache(),
});
const CREATE_POST = gql`
mutation CreatePost($title: String!, $content: String!) {
createPost(title: $title, content: $content) {
id
title
content
}
}
`;
const variables = {
title: 'New Post',
content: 'This is the content of the new post.',
};
client.mutate({
mutation: CREATE_POST,
variables: variables,
})
.then(response => {
console.log('Post created:', response.data.createPost);
})
.catch(error => {
console.error('Error creating post:', error);
});
以上示例使用ApolloClient
创建了一个Apollo客户端实例,并定义了一个名为CREATE_POST
的突变查询。然后,通过调用client.mutate()
方法执行突变操作,并传递突变查询和变量。最后,使用.then()
处理成功的响应,或使用.catch()
处理错误。