溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

如何在React中使用GraphQL訂閱實(shí)現(xiàn)實(shí)時(shí)數(shù)據(jù)更新

發(fā)布時(shí)間:2024-06-17 11:41:50 來源:億速云 閱讀:85 作者:小樊 欄目:web開發(fā)

在React中使用GraphQL訂閱實(shí)現(xiàn)實(shí)時(shí)數(shù)據(jù)更新的步驟如下:

  1. 安裝所需的庫(kù): 首先需要安裝相關(guān)的庫(kù)。可以使用apollo-client@apollo/react-hooks來與GraphQL服務(wù)端通信,以及subscriptions-transport-ws用于訂閱實(shí)時(shí)更新。
npm install @apollo/client @apollo/react-hooks subscriptions-transport-ws
  1. 配置Apollo Client: 在React應(yīng)用的根組件中配置Apollo Client。包括設(shè)置GraphQL服務(wù)端的URL和WebSocket鏈接。
import { ApolloClient, InMemoryCache, createHttpLink, split } from '@apollo/client';
import { WebSocketLink } from '@apollo/client/link/ws';
import { getMainDefinition } from '@apollo/client/utilities';
import { ApolloProvider } from '@apollo/react-hooks';

const httpLink = createHttpLink({
  uri: 'http://your-graphql-server-url',
});

const wsLink = new WebSocketLink({
  uri: 'ws://your-graphql-server-url',
  options: {
    reconnect: true
  }
});

const link = split(
  ({ query }) => {
    const definition = getMainDefinition(query);
    return definition.kind === 'OperationDefinition' && definition.operation === 'subscription';
  },
  wsLink,
  httpLink,
);

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

const App = () => (
  <ApolloProvider client={client}>
    <YourComponent />
  </ApolloProvider>
);
  1. 訂閱數(shù)據(jù)更新: 在需要實(shí)時(shí)更新數(shù)據(jù)的組件中使用useSubscription鉤子來訂閱數(shù)據(jù)更新。
import { useSubscription } from '@apollo/react-hooks';
import { gql } from '@apollo/client';

const SUBSCRIPTION_QUERY = gql`
  subscription {
    yourSubscription {
      id
      data
    }
  }
`;

const YourComponent = () => {
  const { data, loading } = useSubscription(SUBSCRIPTION_QUERY);

  if (loading) return <div>Loading...</div>;

  return (
    <div>
      <p>ID: {data.yourSubscription.id}</p>
      <p>Data: {data.yourSubscription.data}</p>
    </div>
  );
};

通過以上步驟,就可以在React中使用GraphQL訂閱實(shí)現(xiàn)實(shí)時(shí)數(shù)據(jù)更新了。當(dāng)GraphQL服務(wù)端的數(shù)據(jù)發(fā)生變化時(shí),React組件會(huì)自動(dòng)更新顯示最新的數(shù)據(jù)。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI