I'm trying to make a query in Apollo Client with React without returning a JSX component, just an object (the data
object that is received when making a common query to Apollo Server).
I tried using <Query />
component, but it returns me a React Node and I only need an object. The documentation only explain methods that return JSX components at some point, when all that I'm looking to do is send a request and process the response in a callback.
Actually I'm trying this way (I'm using TypeScript in React):
import React from 'react';
import { withApollo } from 'react-apollo';
import gql from 'graphql-tag';
const MY_QUERY = gql`
query MY_QUERY {
myQuery {
attr1
attr2
}
}
`;
const res = ({ client }: { client: any }) =>
client
.query(MY_QUERY)
.then((data: { data: any }) => data);
withApollo(res);
console.log(res);
With this, what I'm looking is for a object like
{
"data": {
"myQuery": [
{
"attr1": "something 1...",
"attr2": "another thing 1..."
},
{
"attr1": "something 2...",
"attr2": "another thing 2..."
},
{
"attr1": "something 3...",
"attr2": "another thing 3..."
}
]
}
}
But what I'm receiving from the browser is
ƒ WithApollo(props) {
var _this = _super.call(this, props) || this;
_this.setWrappedInstance = _this.setWrappedInstance.bind(_this);
return _this;
}
Any suggestion?
Executing a query To run a query within a React component, call useQuery and pass it a GraphQL query string. When your component renders, useQuery returns an object from Apollo Client that contains loading , error , and data properties you can use to render your UI.
Apollo Client's useQuery hook leverages React's Hooks API to bind a query to a component, enabling that component to render a query's results immediately. The useQuery hook encapsulates the logic for retrieving your data, tracking loading and error states, and updating your UI.
Apollo GraphQL no longer requires Redux. Apollo Client automatically catches the data and normalizes new data in query responses and after mutation.
Try this instead
class anyComponent extends React.Component<Props> {
state = {
results: null,
}
componentDidMount = async () => {
const {client} = this.props;
res = await client.query({query: MY_QUERY});
console.log(res);
this.setState({results: res})
}
render() {
// check if any results exist (just an example)
return results ? <AnyJsx results={results}/> : null;
}
}
export default withApollo(anyComponent);
You were console logging the function instead of calling it to get its result
You may need some lifecycle functions like componentDidMount
to retrieve data
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With