Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

209
Views
Is it possible to use Graphql query with React Class component?

I need to transform this component to a class component, how can I replace useQuery hook?

  import {useQuery, gql} from "@apollo/client";

const getBooks = gql`
  {
    books {
      name
    }
  }
`;

function BookList() {
  const {data} = useQuery(getBooks);
      
  console.log(data);
  return (
    <div>
      <ul id="book-list">
        {data.books.map(book => (
          <li key={book.id}>{book.name}</li>
        ))}
      </ul>
    </div>
  );
}

export default BookList;
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Solution-1

You can either use a higher-order component as Mark mentioned and you can achieve so by making a component like:

    const withHook = (Component) => {
      return WrappedComponent = (props) => {
        const someHookValue = useSomeHook();
        return <Component {...props} someHookValue={someHookValue} />;
       }
    }

then you can use it like:

class Foo extends React.Component {
  render(){
    const { someHookValue } = this.props;
    return <div>{someHookValue}</div>;
  }
}

export default withHook(Foo);

Source for the above snippets.

Solution-2

If you're not interested in using apollo clint, you can fetch data from your server normally as you fetch any API, using AXIOS or normal fetch or you can use graphql-request library to do so:

import { request, gql } from 'graphql-request';

const getBooks = gql`
  {
    books {
      name
    }
  }
`;

function BookList() {
  request('https://<server-link>', getBooks).then((data) => (
    <div>
      <ul id="book-list">
        {data.books.map(book => (
          <li key={book.id}>{book.name}</li>
        ))}
      </ul>
    </div>
  ));
      
}

export default BookList;

about 4 years ago · Juan Pablo Isaza Report

0

https://softchris.github.io/pages/graphql-apollo-client.html#query

Here you can find the answer. Here is a way to make a query without useQuery.

I tried it in my project, and it works.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!