Apollo GraphQL has initiated the detection of a new subscription

My approach involves utilizing graphql-ws for subscribing to GraphQL events. I rely on the Observable interface to listen to these events. Although I can use the error callback to identify when a subscription fails to start, it is challenging to determine if it has successfully started.

When an event occurs, the next function is triggered. However, I am interested in encapsulating the Observable within a Promise and await its commencement before proceeding with the subscription.

While awaiting resolution of the promise, I aim to display a progress bar. Although I can reject the promise using the error, I am struggling to find a method to resolve it once the server responds to the subscription request.

function toObservable(operation) {
  return new Observable((observer) =>
    client.subscribe(operation, {
      next: (data) => observer.next(data),
      error: (err) => observer.error(err),
      complete: () => observer.complete(),
    }),
  );
}

Answer №1

Observing the connection status is possible while initializing the client:

    const _wsClient = createClient({
        url: process.env.GRAPHQL_WS_ENDPOINT!,
        on: {
            connected: () => {
                console.log("_CONNECTED!!!")
            },
            closed: () => {
                console.log("_CLOSED!!!")
            },
            error: () => {
                console.log("_ERROR!!!")
            }
        },
    })

Additional events can be monitored through the 'on' method as mentioned in the documentation

While it may not align with the Promise technique you referenced, utilizing a global state handler like redux or a globally scoped observable can aid in sharing the connection status across instances/components

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error: module 'next/react' not found

Recently delving into next.js, I encountered an error after creating a project with npx create-next-app. Oddly enough, the app still runs despite this issue. { "resource": "/E:/codes/news-website/news-website/pages/index.js", ...

Is Your CanvasJS Chart Traveling in Reverse?

My charts are displaying dates in reverse order, can anyone help me figure out what's causing this issue? I've checked the documentation but couldn't find anything that would explain this problem. Link to documentation: Here is a screensh ...

Enhance Data3 Sankey to disperse data efficiently

There are a few instances where the D3 Sankey spread feature is showcased here. However, it seems that this specific function is not included in the official D3 Sankey plugin. Is there anyone who can assist me in obtaining the code for the Spread function ...

Internet Explorer causing problems with JQuery

I encountered an error with the following code snippet: jQuery.post('/user/result/generate',{ 'id': getHidden() }, function(html) { $('#result').html(html); }); The error message is: ...

While validating in my Angular application, I encountered an error stating that no index signature with a parameter of type 'string' was found on type 'AbstractControl[]'

While trying to validate my Angular application, I encountered the following error: src/app/register/register.component.ts:45:39 - error TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used ...

Using useState to initialize a long value

Obtaining a very large state from JSON can be challenging, especially when it consists of at least 50 lines. During page generation, an error like "there is no such value" may occur if the initial value is not set and the interface is not assigned properl ...

Once the PHP page loads, it becomes challenging for me to dynamically change values in JavaScript

Within my code snippet below, I am aiming to modify the initial value using a slider. The slider appears to be functioning correctly; however, it is not updating the values of timeout as indicated beneath the line $('ul.<?php echo $this->session ...

Utilizing headless Chrome to automatically capture AJAX requests

Chrome officially supports running the browser in headless mode, allowing for programmatic control through the Puppeteer API and/or the CRI library. I've thoroughly explored the documentation but have not discovered a method to programmatically captu ...

NodeJS's pending ajax post using SailsJS

I'm experiencing an issue with processing AJAX data in my sailsJS app. The ajax post data always stays in the pending state, here is the code from my view: <script type="text/javascript"> $('#submit').click(function(){ $.ajax ...

Is there a way to identify the top five elements that are most frequently occurring in the array?

I've successfully found the element that appears the most in an array, but now I'm facing a new challenge where I need to identify the top 5 elements that appear most frequently. Here is the array: [ "fuji", "acros", &q ...

Trying out the fetch api with Jest in a React Component: A step-by-step guide

As a newcomer to test driven development, I stumbled upon a section that talked about testing/mocking a fetch API. However, I am facing issues while trying to write my own test. In order to practice this concept, I created a simple weather app where I atte ...

Why does the error message "DeprecationWarning: 'originalKeywordKind' deprecated" keep popping up while I'm trying to compile my project?

Upon completing the compilation of my project, I encountered the error message provided below. What does this signify and what steps can I take to resolve it? - info Linting and checking validity of types DeprecationWarning: 'originalKeywordKind' ...

Changing the application's state from within a child component using React and Flux

UPDATE It seems that my initial approach was completely off base. According to the accepted answer, a good starting point is the TodoMVC app built with React + Flux and available on GitHub. I am currently working on a small React + Flux application for ed ...

When the input field is cleared, JavaScript will not be able to recognize its contents

Having an issue with my function that fetches results, <script language="javascript"> function fetchResult(value){ url="ajax_fetch.php?st=usr&q="+value; ajax(url); } fetchResult(" "); </script&g ...

The .val() function in jQuery can sometimes give different results when used on input elements with placeholder text in Firefox compared to Chrome

After analyzing the given HTML code, I've noticed discrepancies in the values returned by jQuery in Firefox and Chrome: HTML: <input type="text" name="name" id="name" placeholder="Type Here"> <input type="email" name="email" id="email" plac ...

"Key challenges arise when attempting to execute the node app.js script through the terminal due to various middleware compatibility

I'm a beginner with node.js and I've encountered an issue while trying to run my node app.js file after incorporating a new file named projects.js which contains the following JS code: exports.viewProject = function(req, res){ res.render(" ...

I require the ability to access a reference parameter with a dynamically changing name within a Vue template

<div v-for="x in 4" :class="(images[x] === null) ? 'not-removable' : 'removable'" class="img-container"> <input style="display: none" type="file" ...

Exploring the differences between a callback function and an asynchronous

In the code snippet below, I have implemented handling for SIGINT and SIGTERM signals in a node.js application. // quit on ctrl+c when running docker in terminal process.on('SIGINT', async () => { console.info('Got SIGINT (aka ctrl+c in ...

Utilize Javascript to trigger AJAX refreshes only when necessary

I have developed a web application that displays data fetched from an AJAX request to a PHP script on the same server. This particular application involves playing music from Spotify, and in order to ensure the displayed information is always up-to-date ...

Escape sequences do not seem to be functioning properly when using innerHTML

I am facing an issue where a string containing HTML escape characters (such as < and >) needs to be rendered inside a div using innerHTML. The intention is for the escaped characters to appear as text rather than as actual HTML, but they still render ...