Sign up for Hasura Newsletter
Loading...

Subscription

Apolloの初期セットアップの際に、Apollo Boostで必要なdepdendenciesをインストールします。ただし、subscriptionsはApollo Boostがサポートしていない高度なユースケースです。そのため、subscriptionsのセットアップには、より多くのdepdendenciesをインストールする必要があります。

React Apollo Subscriptionsのセットアップ

+ $ npm install subscriptions-transport-ws --save

ここでは、 ApolloClient インスタンスを更新して、subscriptionサーバー指向に設定します。

src/components/App.js を開いて、importを以下の通り更新します。

githubsrc/components/App.js
- import { ApolloClient, ApolloProvider, InMemoryCache, HttpLink } from '@apollo/client';
+ import { ApolloClient, ApolloProvider, InMemoryCache } from '@apollo/client';
+ import { WebSocketLink } from "@apollo/client/link/ws";

createApolloClient関数を更新して、WebSocketLinkを統合します。

const createApolloClient = (authToken) => {
return new ApolloClient({
- link: new HttpLink({
+ link: new WebSocketLink({
- uri: 'https://hasura.io/learn/graphql',
+ uri: 'wss://hasura.io/learn/graphql',
+ options: {
+ reconnect: true,
+ connectionParams: {
headers: {
Authorization: `Bearer ${authToken}`
}
+ }
+ }
}),
cache: new InMemoryCache(),
});
};

なお、HttpLinkをWebSocketLinkに置き換えるため、すべてのGraphQL queriesは単一のWebSocket接続を経由する点に注意してください。

Did you find this page helpful?
Start with GraphQL on Hasura for Free
  • ArrowBuild apps and APIs 10x faster
  • ArrowBuilt-in authorization and caching
  • Arrow8x more performant than hand-rolled APIs
Promo
footer illustration
Brand logo
© 2024 Hasura Inc. All rights reserved
Github
Titter
Discord
Facebook
Instagram
Youtube
Linkedin