Search code examples
apollographql-subscriptions

Apollo GraphQL unsubscribe seems to be broken


We are using Apollo GraphQL with subscriptions (via websockets) in a node.js backend and a react frontend. The app provides a list of devices. When a user clicks on one device he gets the monitoring data for the device with live updates (from the subscription). When the user clicks on another device the subscription is stoppen, the data for the next device is being loaded and subscribed.

I pasted the messages from the websocket connection below. I first tried to paste the raw log here, but the screenshot is much easier to read.

Please ignore the ids 1-5. Important for my problem is id 6 and 7. The id is created when clicking on the first device (at 11:15:35) and then the details are closed so the subscription is stopped (at 11:15:36). Now the user clicks another device and starts subscription 7. Some seconds later the system pushes data for both, the 6th and 7th subscription.

Is there something I can do so "stop" actually means "stop" or is this a bug?

Screenshot of the websocket messages

Edit: as requested, here is the code I use to subscribe/unsubscribe (I had to cut some parts due to company regulations)

    const subscription = useRef(null)
    const { loading, data, error, subscribeToMore } = useQuery(getDevice, { variables: { deviceId } })
    useEffect(() => {
        return () => {
            if (!subscription.current) return
            subscription.current()
            subscription.current = null
        }
    }, [deviceId])
    if (!subscription.current) {
        subscription.current = subscribeToMore({
            document: geDeviceSubscription,
            variables: {
                deviceId
            },
            updateQuery: (prev, { subscriptionData }) => ({ device: subscriptionData.data.subscribeDevice })
        })
    }

Edit 2: It is for sure not my clients issue as it also happens if the use the GraphiQL gui, start a subscription and stop it again. The new data is not displayed but it is visible in the websocket connection in the network tab of the browser (chrome).


Solution

  • It seems to have been a bug in an older apollo graphql or nestjs-apollo-graphql version (We use those frameworks in the backend). After upgrading all the backend dependencies to "latest", the bug doesn't seem to persist.