useQuery返回未定义,但是在gql操场上返回数据 [英] useQuery returns undefined, But returns data on gql playground

查看:161
本文介绍了useQuery返回未定义,但是在gql操场上返回数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

"@apollo/react-hooks": "^3.1.3",
"apollo-client": "^2.6.8",

Apollo客户端在react应用上返回未定义,但在gql操场上返回数据,我不明白为什么它不能在客户端上工作而在graphql操场上工作.

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.

架构

我为用户查询定义了联合,以进行错误处理.

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
}

查询解析器

 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)
      }
    }
  }

在gql操场上查询

在graphql操场上,查询有效.

on graphql playground, query works.

在客户端

 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运行,但返回undefiend.

useQuery runs but returns undefiend.

推荐答案

这是一个较晚的答案,但是我遇到同样的问题,我的playGround返回了正确的响应,但没有useQuery挂钩.

It's kind of a late answer but I had the same issue where my playGround returned a correct response but not the useQuery hook.

我的问题是,给您查询的变量(在您的情况下为'id')的类型为String而不是Number.

My problem was that the variable given to the query, in your case 'id', was of type String instead of Number.

这篇关于useQuery返回未定义,但是在gql操场上返回数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆