BraveEvidence
BraveEvidence

Reputation: 85

Apollo useSubscription hook not emitting new data

I have created subscription whenever a new post is added. The subscription works fine on the graphiql interface.

Here is my react code to use useSubscription hook

export const SUSCRIBE_POSTS = gql`
  {
    subscription
    posts {
      newPost {
        body
        id
        createdAt
      }
    }
  }
`;

 const {
    loading: suscriptionLoading,
    error: subscriptionError,
    data: subscriptionData,
  } = useSubscription(SUSCRIBE_POSTS);

when I try to console log subscriptionData I get nothing. when I add a post it is saved in database correctly, the useQuery hook for getting posts also work fine, but when I add a new post I don't see the subscription data. I can't see anything wrong in the console as well. When I log suscriptionLoading, Ido get true at the start. I am not sure how to debug this.

The client setup is done correctly according to the docs https://www.apollographql.com/docs/react/data/subscriptions/

and here is the code

const httpLink = createHttpLink({
  uri: "http://localhost:4000/",
});

const wsLink = new WebSocketLink({
  uri: `ws://localhost:4000/graphql`,
  options: {
    reconnect: true,
  },
});

const authLink = setContext(() => {
  const token = localStorage.getItem("jwtToken");
  return {
    headers: {
      Authorization: token ? `Bearer ${token}` : "",
    },
  };
});

const link = split(
  // split based on operation type
  ({ query }) => {
    const definition = getMainDefinition(query);
    return (
      definition.kind === "OperationDefinition" &&
      definition.operation === "subscription"
    );
  },
  wsLink,
  authLink.concat(httpLink)
);

const client = new ApolloClient({
  link: link,
  cache: new InMemoryCache(),

});

export default (
  <ApolloProvider client={client}>
    <App />
  </ApolloProvider>
);

Upvotes: 1

Views: 1836

Answers (1)

True
True

Reputation: 736

export const SUSCRIBE_POSTS = gql`
    subscription
    posts {
      newPost {
        body
        id
        createdAt
      }
    }
`;

Can you try to remove the most-outside brackets of subscription gql?

Upvotes: 2

Related Questions