I am making a GraphQL request using below gql query.
export const GET_DETAILS = gql`
query ($id: String) {
country(id: $id) {
currency
phone
}
}
`;
When I check its response in network tab of chrome dev tools I see something below:
But when I log it out in code below, it returns undefined.
render() {
return (
<div>
<Query query={GET_DETAILS} variables={{ id: `${this.props.match.params.code}` }}>
{(loading, error, data) => {
{console.log(data)} // ----> Here it is undefined
return (
<div>
</div>
);
}}
</Query>
</div>
);
}
Any idea what am I doing wrong and how to fix?
I had a similar scenario.
I copied a React component from one project to another, along with the gql query.
const { loading, data } = useQuery<NotificationsData>(GET_NOTIFICATIONS);
This was working fine on the older project and not in the new one. I could see the data being returned in the network tab, but it was still undefined in my component. Even when loading changed to false.
This was my gql query
query UserDetails {
userDetails {
id
username
first_name
last_name
avatar_url
initials @client
}
}
The issue here was the line
initials @client
so, i forgot to add the resolver for the @client field here, in my index.tsx file.
something like:
const client = new ApolloClient({
cache: new InMemoryCache(),
resolvers: {
UserEntity: {
initials: (user, _args, { cache }) => {
let initials = user.first_name[0];
if (user.last_name && user.last_name.length) {
initials = initials + user.last_name[0];
}
return initials;
},
},
},
});
After adding this, the data started to show up just fine in my component.
Like all API requests, GraphQL queries are asynchronous, so the data cannot be logged if it has not arrived from the server yet, which it looks like you are trying to do.
If you check to make sure the data exists before logging it it will work.
if (data) {
console.log(data);
}
The render props function used by the Query
component is passed an object as its first and only parameter. loading
, error
and data
are all properties on that object. In other words, using destructuring syntax, you can access them like this:
{({ loading, error, data }) => {
console.log(data)
...
}
This is equivalent to
{(props) => {
console.log(props.data)
...
}
Of course, because GraphQL requests are asynchronous, data
will be undefined until the request completes so your code needs to reflect that fact as well.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.