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

Viewed 707

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;
2 Answers

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;

Related