Sign up for Hasura Newsletter
Loading...

SubscriptionとRenderの結果オブジェクトの作成

graphql subscriptionを定義します。

src/components/OnlineUsers/OnlineUsersWrapper.js を開いて、他のインポートコードの後に以下のコードを追加します

githubsrc/components/OnlineUsers/OnlineUsersWrapper.js
- import React, { useEffect, useState } from "react";
+ import React, { useEffect, Fragment, useState } from "react";
- import { useMutation, gql } from "@apollo/client";
+ import { useMutation, useSubscription, gql } from "@apollo/client";

@apollo/client から useSubscription をインポートしてから、オンラインユーザーのデータを取得するために、上記の通りgraphql subscriptionのquery定義します。

続いて、 useSubscription を使ってReactフックをsubscription queryに渡します:

+ const { loading, error, data } = useSubscription(
+ gql`
+ subscription getOnlineUsers {
+ online_users(order_by: { user: { name: asc } }) {
+ id
+ user {
+ name
+ }
+ }
+ }
+ `
+ );
+
+ if (loading) {
+ return <span>Loading...</span>;
+ }
+ if (error) {
+ console.error(error);
+ return <span>Error!</span>;
+ }
+ if (data) {
+ onlineUsersList = data.online_users.map(u => (
+ <OnlineUser key={u.id} user={u.user} />
+ ));
+ }
+
+ return (
+ <div className="onlineUsersWrapper">
+ <Fragment>
+ <div className="sliderHeader">
+ Online users - {onlineUsersList.length}
+ </div>
+ {onlineUsersList}
+ </Fragment>
+ </div>
+ );
+ };
export default OnlineUsersWrapper;

これで実データが取得できたので、モックのオンラインユーザーステートを削除します

const OnlineUsersWrapper = () => {
- const onlineUsers = [{ name: "someUser1" }, { name: "someUser2" }];
-
- const onlineUsersList = [];
- onlineUsers.forEach((user, index) => {
- onlineUsersList.push(<OnlineUser key={index} index={index} user={user} />);
- });
-
- return (
- <div className="onlineUsersWrapper">
- <div className="sliderHeader">Online users - {onlineUsers.length}</div>
- {onlineUsersList}
- </div>
- );
};

仕組みについて

useQueryuseMutation のReactフックのようなプロパティを返す useSubscription Reactフックを使用していますdata プロパティは、作成したqueryに応じてリアルタイムデータの結果を提供します。

Reactアプリを更新してオンラインで確認してください。オンラインには他のユーザーもいるかもしれませんが、驚かないでください。

完璧です。GraphQLのQuery、Mutation、Subscriptionsの実装が完了しました。

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