在React项目中使用Apollo客户端来实现GraphQL订阅可以通过以下步骤完成。
首先, 需要确保项目中已安装 Apollo client、subscriptions-transport-ws 和 graphql。
npm install apollo-client subscriptions-transport-ws graphql --save
使用 subscriptions-transport-ws
包提供的 SubscriptionClient
构造函数来创建 WebSocket 客户端。
import { SubscriptionClient } from "subscriptions-transport-ws";
const subscriptionClient = new SubscriptionClient("ws://localhost:4000/graphql", {
reconnect: true,
});
以上代码创建了一个WebSocket客户端,它将与相应的GraphQL服务器建立连接。
使用 apollo-client
包提供的 ApolloClient
构造函数来创建Apollo客户端。在这个构造函数中,将 subscriptionClient
实例作为 link
属性传递,使用 InMemoryCache
作为数据缓存。
import { ApolloClient } from "apollo-client";
import { InMemoryCache } from "apollo-cache-inmemory";
import { WebSocketLink } from "apollo-link-ws";
const wsLink = new WebSocketLink(subscriptionClient);
const apolloClient = new ApolloClient({
link: wsLink,
cache: new InMemoryCache(),
});
现在可以使用 react-apollo
包提供的 Subscription
组件来定义GraphQL订阅。
import { gql } from "apollo-boost";
import { Subscription } from "react-apollo";
const SUBSCRIPTION_QUERY = gql`
subscription SomeSubscription {
someEvent {
id
message
}
}
`;
function MyComponent() {
return (
{(result) => {
if (result.loading) {
return Loading...;
}
if (result.error) {
return Error: ${result.error.message};