阿波罗useSubscription钩子不发出新数据

时间:2020-04-11 14:40:16

标签: reactjs react-apollo apollo-client graphql-subscriptions

每当添加新帖子时,我都会创建订阅。订阅可以在graphiql界面上正常工作。

这是我使用useSubscription钩子的反应代码

export const SUSCRIBE_POSTS = gql`
  {
    subscription
    posts {
      newPost {
        body
        id
        createdAt
      }
    }
  }
`;

 const {
    loading: suscriptionLoading,
    error: subscriptionError,
    data: subscriptionData,
  } = useSubscription(SUSCRIBE_POSTS);

当我尝试管理日志subscriptionData时,我一无所获。当我添加帖子时,它可以正确保存在数据库中,用于获取帖子的useQuery钩也可以正常工作,但是当我添加新帖子时,看不到订阅数据。我在控制台中也看不到任何错误。当我登录suscriptionLoading时,Ido一开始就正确。我不确定该如何调试。

根据文档https://www.apollographql.com/docs/react/data/subscriptions/

正确完成了客户端设置

这是代码

const httpLink = createHttpLink({
  uri: "http://localhost:4000/",
});

const wsLink = new WebSocketLink({
  uri: `ws://localhost:4000/graphql`,
  options: {
    reconnect: true,
  },
});

const authLink = setContext(() => {
  const token = localStorage.getItem("jwtToken");
  return {
    headers: {
      Authorization: token ? `Bearer ${token}` : "",
    },
  };
});

const link = split(
  // split based on operation type
  ({ query }) => {
    const definition = getMainDefinition(query);
    return (
      definition.kind === "OperationDefinition" &&
      definition.operation === "subscription"
    );
  },
  wsLink,
  authLink.concat(httpLink)
);

const client = new ApolloClient({
  link: link,
  cache: new InMemoryCache(),

});

export default (
  <ApolloProvider client={client}>
    <App />
  </ApolloProvider>
);

1 个答案:

答案 0 :(得分:1)

export const SUSCRIBE_POSTS = gql`
    subscription
    posts {
      newPost {
        body
        id
        createdAt
      }
    }
`;

您可以尝试删除订阅gql的最外括号吗?