【问题标题】:Graphql subscription not getting client-side variablesGraphql 订阅未获取客户端变量
【发布时间】:2021-07-28 02:27:36
【问题描述】:

我正在尝试使用 apollo-client useSubscription hook 订阅 graphql-yoga 订阅

import React from 'react';
import {useSubscription,gql} from '@apollo/client';

const SUB_NEW_MSG = gql`
    subscription SUB_NEW_MSG($chatRoom:ID!)
    {
        newMessage(chatRoom:$chatRoom)
    }`;


function NewMsg(){

    const { loading,error,data } = useSubscription(SUB_NEW_MSG,{
        variables:{
            chatRoom: "608851227be4796a8463607a",
        },
    });
    
    if(loading) return <p>loading...</p>;
    if(error) return <p>{error}</p>;
    
    console.log(data);
    return <h4>New Message:{data.newMessage}</h4>;
}

Network Status

但是给出了一个错误- 错误:对象作为 React 子项无效(发现:错误:未提供所需类型“ID!”的变量“$chatRoom”。)。如果您打算渲染一组子项,请改用数组。

后端的架构是

type Subscription{
    newMessage(chatRoom: ID!): String!
}

解析器是

const { pubsub } = require("../helper");
const { withFilter } = require("graphql-yoga");

module.exports = {
    Subscription: {
        newMessage: {
            subscribe: withFilter(
                () => pubsub.asyncIterator("newMessage"),
                (payload, variables) => {
                    console.log(payload.query, variables, "HALO");
                    return payload.chatRoom === variables.chatRoom;
                }
            ),
        },
    },
};

但是当我像下面这样传递查询时,没有变量可以使用订阅挂钩。然后它就可以工作了

const SUB_NEW_MSG = gql`
    subscription SUB_NEW_MSG
    {
        newMessage(chatRoom:"608851227be4796a8463607a")
    }`;

我该怎么办?有什么解决方法吗?

【问题讨论】:

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


    【解决方案1】:

    把你的查询改成这个,然后测试一下。

    const SUB_NEW_MSG = gql`
      subscription SUB_NEW_MSG($chatRoom: String!) {
        newMessage(chatRoom: $chatRoom)
      }
    `;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-03
      • 2022-12-12
      • 2023-01-31
      • 2020-03-21
      • 2019-07-19
      • 1970-01-01
      • 2019-01-18
      • 1970-01-01
      相关资源
      最近更新 更多