TypeError: Cannot read properties of undefined (reading 'watchQuery')

Viewed 1165

I try to make graphql connection from react app. My index.js:

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { ApolloProvider } from '@apollo/client'
import { createClient } from 'graphql-ws';

const client = createClient({
  url: '<some url>',
  connectionParams: {
    authToken: '<some token>',
  },
});

ReactDOM.render(
  <ApolloProvider client={client}>
    <App />
  </ApolloProvider>
  ,
  document.getElementById('root')
);

My App.js:

import { gql, useSubscription, useQuery } from '@apollo/client'


const QUERY = gql`query SomeName{
  test_tablesList {
    items {
      id
      num
    }
  }
}`;


function App() {
  const { data, loading } = useQuery(QUERY);
  return (
    <h1>Hi there</h1>
  );
}

export default App;

When I run it console argues:

useQuery.ts:31 Uncaught TypeError: Cannot read properties of undefined (reading 'watchQuery') at useQuery (useQuery.ts:31:1) at App (App.js:25:1)

react-dom.development.js:18525 The above error occurred in the component:

at App (http://localhost:3000/main.cf5965058b2b7700d166.hot-update.js:48:63)
at ApolloProvider (http://localhost:3000/static/js/bundle.js:51749:19)

What do I do wrongly?

2 Answers

My error is here - import { createClient } from 'graphql-ws'; I had to take it from Apollo client.

You can try this solution :

  • Create one file in src directory called ApolloClient.js
import { ApolloClient, InMemoryCache, HttpLink } from "@apollo/client";
const client = new ApolloClient({
  link: new HttpLink({
    uri: "PUT-HERE-URL-TO-GRAPHQL-END-POINT",
    headers: {
      // PUT-HERE-ANY-HEADER-VARS-IF-EXISTS
    },
  }),
  cache: new InMemoryCache(),
});
export default client;

  • Inside your index.js
import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import { ApolloProvider } from "@apollo/client";
import client from "./ApolloClient";

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <React.StrictMode>
    <ApolloProvider client={client}>
      <App />
    </ApolloProvider>
  </React.StrictMode>
);

  • Finally call the graphql query inside your component App.js
import { gql, useSubscription, useQuery } from '@apollo/client'


const QUERY = gql`query SomeName{
  test_tablesList {
    items {
      id
      num
    }
  }
}`;


function App() {
  const { data, loading } = useQuery(QUERY);
  return (
    <h1>Hi there</h1>
  );
}

export default App;

Apollo client docs

Related