使用 useQuery apollo 客户端通过 id 获取数据不起作用

时间:2021-06-15 19:14:15

标签: apollo apollo-client react-apollo apollo-server

意图:

尝试根据动态 id 从 apollo 客户端进行查询。已成功签入正在工作的服务器提供的接口...并尝试从客户端执行相同操作。

从文档看来我需要使用我所做的变量。

问题:

使用变量的查询看起来不错,但我在客户端中未定义。

在 graphql API 中工作的查询:

query abc {
    getCategoryProduct(id:"NzI1NDc1MTM1") {
      id
      title
      description
      favorited
      published
      price_per_day
      price_per_week
      price_per_month
      price_per_weekend
      picture
      pictures {
        id
        url
      }
      createdAt
      updatedAt
    }
  }

客户端有问题的代码

const GETDETAILS = gql`
  query abc($id: String!) {
    getCategoryProduct(id: $id) {
      id
      title
      description
      favorited
      published
      price_per_day
      price_per_week
      price_per_month
      price_per_weekend
      picture
      pictures {
        id
        url
      }
      createdAt
      updatedAt
    }
  }
`;

const DetailScreen = () => {

  const { loading, error, data } = useQuery(GETDETAILS, {
    variables: { id: "NzI1NDc1MTM1" },
  });

  useEffect(() => {
    if (loading == false) {
      console.log("=====data=====", data);  // DATA IS EMPTY DO NOT NOT WHY??
    } 
  }, [data]);

}

1 个答案:

答案 0 :(得分:0)

我遇到了同样的错误,看起来我已经尝试了所有方法来解决它,包括按照 useQuery returns undefined, But returns data on gql playground 中的说明进行操作,但仍然没有奏效。

稍后,我将变量名称(在您的情况下为 $id)更改为其他名称,因此它与 typeDefs (getCategoryProduct(id:ID)) 中的名称不同,现在它对我有用??。