【问题标题】:Apollo useSubscription hook not emitting new dataApollo useSubscription 挂钩不发出新数据
【发布时间】:2020-07-24 06:41:36
【问题描述】:

每当添加新帖子时,我都会创建订阅。订阅在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>
);

【问题讨论】:

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


    【解决方案1】:
    export const SUSCRIBE_POSTS = gql`
        subscription
        posts {
          newPost {
            body
            id
            createdAt
          }
        }
    `;
    

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

    【讨论】:

      猜你喜欢
      • 2020-06-19
      • 2019-09-14
      • 2020-09-28
      • 2020-09-25
      • 2020-03-04
      • 2020-08-13
      • 1970-01-01
      • 1970-01-01
      • 2020-01-15
      相关资源
      最近更新 更多