问题
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?
回答1:
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
来源:https://stackoverflow.com/questions/54620761/how-to-use-client-query-without-jsx-components-in-apollo-client