Search code examples
reactjsreact-nativegraphqlapolloreact-apollo

Does the Apollo `subscribeToMore` variables have to match the initial query?


Does the Apollo subscribeToMore variables have to match the initial query? For example, if my initial query is

const { data, loading, error } = useQuery(INBOX)

where the variable is from the id verified in the server(not sent from the client)

     async inbox(parent, args, { request, prisma }, info) {
        const id = await getUserId(request)
        if (!user.email) {
            throw new Error('You must be logged in!')
        }
        return prisma.query.user({
            where: {
                id,
            }
        },info)
     }

And if the subscription resolver is like the following:

   newInbox: {
        subscribe: (parent, args, { pubsub }, info) => pubsub.asyncIterator(PUBSUB_NEW_INBOX)
    },

would the subscription data be sent to every client in the database since the subscription itself doesn't have the filtering variable or would it recognize that the initial query already had a variable of its own?

In other words, it is necessary to do something like the following?

 newInbox: {
        subscribe: withFilter(
            (parent, args, { pubsub }, info) => pubsub.asyncIterator(PUBSUB_NEW_INBOX),
            (payload, variables) => payload.newInbox.id === variables.id
        )
    },

by sending a variable from the client?


Solution

  • Yes, your filters must be exactly the same. The reason for this is that the cache is populated with the exact query as the key for this response.

    So if you ask for {queryX, limit:2} this is cached as a different query than {queryX, limit:100}.

    You can actually see this for yourself in the cache if you're using Apollo Dev Tools:

    enter image description here