Skip to content

How is the connection between React and graphql-ws #232

Answered by enisdenjo
hichamlehouedj asked this question in Q&A
Discussion options

You must be logged in to vote

Most of the time you use one of the showcased libraries (Relay, Apollo, Urlq) with React. But, here's a quick and simple example using hooks:

import React, { useEffect, useState } from 'react';
import { createClient } from 'graphql-ws';

const client = createClient({
  url: 'ws://react.over.ws/graphql',
});

export function useGraphQLWS(payload) {
  const [{ value, error, done }, setState] = useState({
    value: undefined,
    error: undefined,
    done: false,
  });

  useEffect(() => {
    const unsubscribe = client.subscribe(payload, {
      next: (value) => setState((state) => ({ ...state, value, done: false })),
      error: (error) => setState((state) => ({ ...state, error, done: true

Replies: 2 comments 3 replies

Comment options

You must be logged in to vote
2 replies
@8ctopotamus
Comment options

@enisdenjo
Comment options

Answer selected by enisdenjo
Comment options

You must be logged in to vote
1 reply
@enisdenjo
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
3 participants
Converted from issue

This discussion was converted from issue #229 on September 09, 2021 14:10.