Socket
Socket
Sign inDemoInstall

react-query-subscription

Package Overview
Dependencies
1
Maintainers
1
Versions
14
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    react-query-subscription

Hook for managing, caching and syncing observables in React


Version published
Weekly downloads
172
decreased by-8.51%
Maintainers
1
Created
Weekly downloads
 

Changelog

Source

1.4.0 (2021-11-07)

✨ Features

  • useSubscription: add onError option (c102b7c), closes #29

Readme

Source

React Query useSubscription hook

GitHub release (latest SemVer) All Contributors Gitpod Ready-to-Code codecov GitHub Workflow Status Snyk Vulnerabilities for GitHub Repo Semantic release npm bundle size GitHub

API Reference

Open in Gitpod

Background

While React Query is very feature rich, it misses one thing - support for streams, event emitters, WebSockets etc. This library leverages React Query's useQuery to provide useSubscription hook for subscribing to real-time data.

General enough solution

React Query useQuery's query function is any function which returns a Promise. Similarly, useSubscription's subscription function is any function which returns an Observable.

Installation

NPM

npm install react-query-subscription react react-query@3 rxjs@7

or

yarn add react-query-subscription react react-query@3 rxjs@7

Use cases

Subscribe to WebSocket

TODO

Subscribe to Event source

import { QueryClientProvider, QueryClient } from 'react-query';
import { ReactQueryDevtools } from 'react-query/devtools';
import { useSubscription, eventSource$ } from 'react-query-subscription';

const queryClient = new QueryClient();

function App() {
  return (
    <QueryClientProvider client={queryClient}>
      <SseExample />
      <ReactQueryDevtools initialIsOpen={false} />
    </QueryClientProvider>
  );
}

function SseExample() {
  const { data, isLoading, isError, error } = useSubscription(
    'some-key',
    () => eventSource$('/api/v1/sse'),
    {
      // options
    }
  );

  if (isLoading) {
    return <div>Loading...</div>;
  }
  if (isError) {
    return (
      <div role="alert">
        {error?.message || 'Unknown error'}
      </div>
    );
  }
  return <div>Data: {JSON.stringify(data)}</div>;
}

GraphQL subscription using graphql-ws

import { QueryClientProvider, QueryClient } from 'react-query';
import { ReactQueryDevtools } from 'react-query/devtools';
import { useSubscription } from 'react-query-subscription';
import { createClient } from 'graphql-ws';
import type { Client, SubscribePayload } from 'graphql-ws';

const queryClient = new QueryClient();

function App() {
  return (
    <QueryClientProvider client={queryClient}>
      <GraphQlWsExample postId="abc123" />
      <ReactQueryDevtools initialIsOpen={false} />
    </QueryClientProvider>
  );
}

const client = createClient({ url: 'wss://example.com/graphql' });

/**
 * @see https://github.com/enisdenjo/graphql-ws#observable
 */
export function fromWsClientSubscription<TData = Record<string, unknown>>(
  client: Client,
  payload: SubscribePayload
) {
  return new Observable<TData | null>((observer) =>
    client.subscribe<TData>(payload, {
      next: (data) => observer.next(data.data),
      error: (err) => observer.error(err),
      complete: () => observer.complete(),
    })
  );
}

interface Props {
  postId: string;
}

interface Comment {
  id: string;
  content: string;
}

function GraphQlWsExample({ postId }: Props) {
  const { data, isLoading, isError, error } = useSubscription(
    'some-key',
    () => fromWsClientSubscription<{ comments: Array<Comment> }>({
      query: `
        subscription Comments($postId: ID!) {
          comments(postId: $postId) {
            id
            content
          }
        }
      `,
      variables: {
        postId,
      },
    }),
    {
      // options
    }
  );

  if (isLoading) {
    return <div>Loading...</div>;
  }
  if (isError) {
    return (
      <div role="alert">
        {error?.message || 'Unknown error'}
      </div>
    );
  }
  return <div>Data: {JSON.stringify(data?.comments)}</div>;
}

Contributors ✨

Thanks goes to these wonderful people (emoji key):


Katarina Anton

💻 🤔 🚧 ⚠️ 🔧 🚇

This project follows the all-contributors specification. Contributions of any kind welcome!

Keywords

FAQs

Last updated on 07 Nov 2021

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc