您好,登錄后才能下訂單哦!
在React中使用GraphQL訂閱實現實時數據更新的步驟如下:
apollo-client
和@apollo/react-hooks
來與GraphQL服務端通信,以及subscriptions-transport-ws
用于訂閱實時更新。npm install @apollo/client @apollo/react-hooks subscriptions-transport-ws
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>
);
useSubscription
鉤子來訂閱數據更新。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訂閱實現實時數據更新了。當GraphQL服務端的數據發生變化時,React組件會自動更新顯示最新的數據。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。