问题
"@apollo/react-hooks": "^3.1.3",
"apollo-client": "^2.6.8",
Apollo client return undefined on react app but return the data on gql playground, I don't understand why don't it works on client-side but works on graphql playground.
Schema
I have defined union for user query for error handling.
type Query {
user(id: ID!): UserReturn!
}
union UserReturn = User | Error
type User {
id: ID!
username: String!
email: String
profileUrl: String
createdAt: Date
ads: [Doc!]!
}
type Error {
message: String
code: ID
}
Query resolver
async user(_, { id }, { User }) {
console.log('query - User')
try {
await delay(1000 * 3)
const user = await User.findById(id).populate('userData')
console.log(user)
if (!user) return {
__typename: 'Error',
message: 'User not found.',
code: id
}
const { _id: id, username, email, createdAt, userData: { profileUrl } } = user
console.log(username)
return {
__typename: 'User',
id,
username,
email,
createdAt,
profileUrl
}
} catch (err) {
console.log(err)
return {
__typename: 'Error',
message: 'Something went wrong while getting user.',
code: LogBack(err, `query/user?id=${id}`, __filename)
}
}
}
When querying on gql playground
on graphql playground, query works.
On the client-side
const { data } = useQuery(
gql`query user($id: ID!) {
user(id: $id) {
__typename
... on User {
id
username
email
profileUrl
createdAt
# ads
}
... on Error {
message
code
}
}
}
`,
{
variables: {
id: userId
}
}
);
console.log(data) // undefined
useQuery runs but returns undefiend.
回答1:
something that might help, you know where you call {data} you can also look for error and console.log('Error:',error)
check the apollo client query docs
something like this , and look at the error message, it should help !
import { useQuery } from '@apollo/react-hooks';
import gql from 'graphql-tag';
const GET_GREETING = gql`
query getGreeting($language: String!) {
greeting(language: $language) {
message
}
}
`;
function Hello() {
const { loading, error, data } = useQuery(GET_GREETING, {
variables: { language: 'english' },
});
if (loading) return 'Loading...';
if (error) return `Error! ${error.message}`;
return <h1>Hello {data.greeting.message}!</h1>;
}
回答2:
I'm able to query the ads by adding IntrospectionFragmentMatcher
to my apollo client setup
This helps me to fix
Here how I fix the issue.
import { InMemoryCache, IntrospectionFragmentMatcher } from "apollo-cache-inmemory";
const fragmentMatcher = new IntrospectionFragmentMatcher({
introspectionQueryResultData: {
__schema: {
types: [
{
"kind": "UNION",
"name": "AdsReturn",
"possibleTypes": [
{
"name": "Ads"
},
{
"name": "Error"
}
]
},
],
},
}
});
export default new ApolloClient({
link: ApolloLink.from([errorLink, authLink, httpLink]),
cache: new InMemoryCache({ fragmentMatcher }),
});
来源:https://stackoverflow.com/questions/59920824/usequery-returns-undefined-but-returns-data-on-gql-playground