Graphql subscription not getting client-side variables

493 Views Asked by At

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?

1

There are 1 best solutions below

0
On

Change your query to this, and test it.

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