首页 > 解决方案 > React w/ Apollo & Drupal nodeQuery - 如何定义/传递变量?

问题描述

将 GraphQL 与 React 和 Drupal 一起使用非常有趣,但很少有文档说明如何让它们一起工作。这个按标签提取文章的 nodeQuery 工作得很好,但我还没有看到任何定义如何将变量传递给使用 gqlClient 定义的 nodeQuery 的示例。我在此查询中放置了变量占位符,但我收到一条错误消息:

Unhandled Rejection (Error): GraphQL error: Variable "$limit" is not defined.
GraphQL error: Variable "$offset" is not defined.

有没有人在这方面取得成功?

import gqlClient from "../gqlClient";
import { gql } from "apollo-boost";
export const articleListByTerm = gqlClient.query({
  query: gql`
    {
      nodeQuery(
        limit: $limit
        offset: $offset
        filter: {
          conditions: [
            { operator: EQUAL, field: "type", value: ["article"] }
            { operator: EQUAL, field: "status", value: ["1"] }
            { operator: EQUAL, field: "field_tags.entity.vid", value: ["tags"] }
            {
              operator: EQUAL
              field: "field_tags.entity.name"
              value: ["thiphif"]
            }
          ]
        }
      ) {
        entities {
          entityLabel
          entityBundle
          ... on NodeArticle {
            body {
              value
            }
            fieldImage {
              url
            }
            queryFieldTags {
              entities {
                entityId
                entityLabel
              }
            }
          }
        }
      }
    }
  `,
});

这是查询的调用方式。您可以看到我正在尝试传递变量,希望它们能正常工作但没有运气。

articleListByTerm({
      variables: { offset: 0, limit: 10 },
    }).then(({ data }) =>
      dispatch(receivePostsByTerm(data.nodeQuery.entities))
    );

标签: graphqldrupal-8react-apolloapollo-client

解决方案


好吧 - 我找到了答案:

import gqlClient from "../gqlClient";
import { gql } from "apollo-boost";
let limit = 10;
let offset = 0;
let type = "article";

export const articleListByTerm = gqlClient.query({
  variables: { limit: limit, offset: offset, type: type },
  query: gql`
    query($limit: Int!, $offset: Int!, $type: String!) {
      nodeQuery(
        limit: $limit
        offset: $offset
        filter: {  .... etc ...

我希望这可以帮助别人。绝对对我有帮助。我添加了一个字符串!示例的变量也可以提供帮助。IDK,如果你可以做一个数组。这是一个相当简单的解决方案,只是它没有记录在任何一个地方。我扯了一些零碎的猜测,终于弄明白了。


推荐阅读