"@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.
useQuery can return undefined because: Generally, on the first render cycle, data will be undefined because well, the data is async and does not exist yet on the frontend. The component will render in the loading state in this case with the isLoading flag set to true .
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 useQuery hook is the primary API for executing queries in a React application. We run a query within a React component by calling useQuery and passing it our GraphQL query string. This makes running queries from React components a breeze.
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>;
}
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