【问题标题】:Apollo react hooks array object mutationApollo react hooks 数组对象突变
【发布时间】:2020-09-18 16:12:58
【问题描述】:

所以我正在使用 MongoDB、Apollo、React Native (Expo) 和 Node 做一个 MARN 堆栈

我一直在试图弄清楚如何上传对象数组。即带有一系列镜头的帖子

在阿波罗操场上一切正常:

mutation createPost {
  createPost(
    input: {
      shots: [
        {
          title: "Test test test"
          content: "Test test test"
          image: "https://source.unsplash.com/random/768x768"
        }
        {
          title: "Best best best"
          content: "Test test test"
          image: "https://source.unsplash.com/random/768x768"
        }
      ]
    }
  ) {
    id
    shots {
      id
    }
  }
}

这是我的服务器架构:

  type Post {
    id: ID!
    shots: [Shot]!
  }

  type Shot {
    id: ID!
    title: String
    content: String
    image: String
  }

  input CreatePostInput {
    shots: [ShotInput]!
  }

  input ShotInput {
    title: String!
    content: String!
    image: String!
  }

现在这是我的反应突变,我坚持的部分。因为它正在产生一个错误,我不知道如何修复它。 如果我用静态对象数组替换 $shots,它就可以工作!我需要使用一些花哨的@relation 标签吗?

const CREATE_POST = gql`
  mutation createPost($shots: [ShotInput]) {
    createPost(input: { shots: $shots }) {
      id
      shots {
        id
      }
    }
  }
`;

这就是我触发错误的方式:

<Button
  title="Button"
  onPress={() => {
    createPost({
      variables: { shots: [{ title: 'test', content: 'test', image: 'test' }] },
    });
  }}
/>

这是我无法摆脱的错误

[GraphQL error]: Message: Variable "$shots" of type "[ShotInput]" used in position expecting type "[ShotInput]!"., Location: [object Object],[object Object], Path: undefined

不管这个小障碍,我不得不说阿波罗是蜜蜂的膝盖!太棒了!!!

【问题讨论】:

    标签: graphql apollo react-apollo apollo-client


    【解决方案1】:

    我想通了。我一直都很亲近!!!

    我所缺少的只是一个感叹号“!”在 createPost() 处

    const CREATE_POST = gql`
      mutation createPost($shots: [ShotInput!]! <===== Right here) {
        createPost(input: { shots: $shots }) {
          id
          shots {
            id
          }
        }
      }
    `;
    

    哎呀,好痛!这么多变数在起作用。吸取教训!!!

    【讨论】:

    • 这让我免于数小时的调试! :)
    猜你喜欢
    • 2020-01-11
    • 2021-05-01
    • 2021-09-18
    • 2017-12-28
    • 2019-11-28
    • 2017-02-07
    • 2020-01-25
    • 2020-05-18
    • 2019-10-22
    相关资源
    最近更新 更多