Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@apollo/client error-React Hook "useQuery" is called in function which is neither a React function component or a custom React Hook function

I get the following error when i make graphql api call using @apollo/client

React Hook "useQuery" is called in function "graphqlService" which is neither a React function component or a custom React Hook function react-hooks/rules-of-hooks

Index file:

import { ApolloClient, InMemoryCache, ApolloProvider } from '@apollo/client';

const client = new ApolloClient({
  uri: "http://localhost:3008",
  cache: new InMemoryCache()
});

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

Functional component file:

import React from 'react';
import {  
  useQuery,
  gql
} from "@apollo/client";
import Schema from '../models/schema';

function graphqlService( params : any = {} ) {
  const query = Schema.getPanelData;
  const { data } = useQuery(query, {variables: params});

  if (data) return data;     
}

export default graphqlService;

Class Component file:

this.data = graphqlService(params);

I do not think it is issue in package, i am using same package in same in POC project. There it is working fine. Only difference is i had written all code in same file, here i have written in 2 different files.

like image 677
apps Avatar asked Mar 08 '26 07:03

apps


1 Answers

I had the same issue in a functional component which is for sure correct. I fixed this error message by using a Capital letter for the component name.

Why it needs a capital letter is described in the official docs

Example:

import React from "react";
import Query from "./Query";
import { useQuery } from "@apollo/client";

const ComponentName = () => {
  const { loading, error, data } = useQuery(Query);

  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error :(</p>;
  return (
    ...
  );
};
export default ComponentName;
like image 195
after8 Avatar answered Mar 11 '26 06:03

after8



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!