简体   繁体   中英

Graphql subscription not getting client-side variables

I am trying to subscribe to a graphql-yoga subscription using apollo-client useSubscription hook

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

But gives an error- Error: Objects are not valid as a React child (found: Error: Variable "$chatRoom" of required type "ID." was not provided.), If you meant to render a collection of children. use an array instead.

The schema at the backend is

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

resolver is

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;
                }
            ),
        },
    },
};

But when I pass the query like below,with no variables to useSubscription hook.Then it works

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

What should I do?Are there any workarounds?

Change your query to this, and test it.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM