开发者问题收集

TypeError:无法读取未定义的属性(读取“watchQuery”)

2022-04-01
4755

我尝试从 react 应用程序建立 graphql 连接。 我的 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')
);

我的 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;

当我运行它时,控制台争论:

useQuery.ts:31 未捕获的 TypeError:无法读取未定义的属性(读取“watchQuery”) 在 useQuery(useQuery.ts:31:1) 在 App(App.js:25:1)

react-dom.development.js:18525 组件中发生上述错误:

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

我做错了什么?

2个回答

我的错误在这里 - 从“graphql-ws”导入{createClient}; 我必须从Apollo客户端获取它。

user18668497
2022-04-01

您可以尝试此解决方案:

  • 在 src 目录中创建一个名为 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;
  • 在您的 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>
);
  • 最后在您的组件 App.js
  • 中调用 graphql 查询
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 客户端文档

Ahmed Mahmoud
2022-05-30