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;
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.
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;
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.