【问题标题】:Apollo GraphQL mutation: Variable is not defined by operationApollo GraphQL 突变:变量未由操作定义
【发布时间】:2021-04-17 03:30:40
【问题描述】:

我能够让 graphql 在客户端和服务器 graphql 操场上正常工作。但是,当我尝试在客户端文件中调用突变时,我最终得到Error: Response not successful: Received status code 400,并且在网络选项卡中我被告知Variable \"$ParkingSpaces\" is not defined by operation \"saveParkingLot\"。假设突变接受一个对象数组。

typeDef 是:

type ParkingSpace {
   id: Int!
   ownerID: String!
   parkingID: String!
  }

input ParkingSpaces {
   id: String!
   ownerID: String!
   parkingID: String!
  }

type Mutation {
    saveParkingLot(parkingLot: [ParkingSpaces]): [ParkingSpace]!
}

解析器正在从数据库中删除现有信息,然后保存新信息

saveParkingLot: async (_, args) => {
      ParkingSpace.collection.drop();
      const parkingArray = new ParkingSpace({
        parkingLot: args.parkingLot,
      });
      parkingArray.save();
      return args.parkingLot;
    },
  },

但代码在客户端失败。我在variables: 中省略了{},因为它由于某种原因会产生语法错误

  const SAVE_PARKING_LOT = gql`
    mutation saveParkingLot($parkingLot: ParkingSpaces!) {
      saveParkingLot(parkingLot: $ParkingSpaces) {
        id
        ownerID
        parkingID
      }
    }
  `;

  const [saveParkingLot] = useMutation(SAVE_PARKING_LOT, {
    onError(err) {
      console.log(err);
    },
  });
  //Mutation fails when called
  const saveParkingLotButton = () => {
       saveParkingLot({
      variables: [
        { id: "0", ownerID: "0", parkingID: "0" },
        { id: "1", ownerID: "1", parkingID: "1" },
        { id: "2", ownerID: "2", parkingID: "2" },
        { id: "3", ownerID: "3", parkingID: "3" },
      ],
    }); 

  };

我哪里做错了?

【问题讨论】:

    标签: node.js reactjs graphql


    【解决方案1】:

    将您的客户端查询更改为:

        mutation saveParkingLot($parkingLot: [ParkingSpaces]) {
          saveParkingLot(parkingLot: $parkingLot) {
            id
            ownerID
            parkingID
          }
        }
    

    在变量部分使用如下:

        variables: {
           parkingLot: [
            { id: "0", ownerID: "0", parkingID: "0" },
            { id: "1", ownerID: "1", parkingID: "1" },
            { id: "2", ownerID: "2", parkingID: "2" },
            { id: "3", ownerID: "3", parkingID: "3" },
          ]
        },
    
    

    参考:https://graphql.org/learn/queries/#variables

    【讨论】:

      猜你喜欢
      • 2019-06-08
      • 2020-04-24
      • 2020-05-18
      • 2019-11-27
      • 2021-11-20
      • 2019-09-09
      • 1970-01-01
      • 2018-11-21
      相关资源
      最近更新 更多