apollographql / apollo-client

:rocket:  A fully-featured, production ready caching GraphQL client for every UI framework and GraphQL server.
https://apollographql.com/client
MIT License
19.38k stars 2.66k forks source link

It is not possible to wait for subscription to subscribe #8886

Closed aleksandrlat closed 3 months ago

aleksandrlat commented 3 years ago

Intended outcome: I want to implement response for mutation to come through websocket. I.e.

But I can call mutation only after I can confirm I subscribed to subscription

Actual outcome: loading is true when I subscribed to subscription

const { loading, data } = useSubscription(subscription)
// loading is true when I subscribed to it

How to reproduce the issue: Just subscribe to subscription

Versions version 3

rossimelthomas commented 1 year ago

any updates?

phryneas commented 3 months ago

I believe you can use the onData callback of useSubscription for this.

function MyComponent() {
  const calledRef = useRef(false);
  const { loading, data } = useSubscription(subscription, {
    onData({ data }) {
      if (!calledRef.current) {
        calledRef.current = true;

        console.log(data)
        // execute your mutation here
      }
    },
  });
}

I believe beyond that, we can't really do a lot here - React doesn't wait for something to happen before rendering, it just synchronously renders your component.

As a result I'm going to close this issue - if you have any further usage questions, please also consider joining our Discord - we try to keep the issue tracker for bug reports and usage questions more in the Discord.

github-actions[bot] commented 3 months ago

Do you have any feedback for the maintainers? Please tell us by taking a one-minute survey. Your responses will help us understand Apollo Client usage and allow us to serve you better.

github-actions[bot] commented 2 months ago

This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs. For general questions, we recommend using StackOverflow or our discord server.