Apollo react hooks array object mutation

北城余情 提交于 2020-06-01 04:44:21

问题


So I am doing a MARN stack using MongoDB, Apollo, React Native (Expo) and Node

I am stuck trying to figure out how to upload an array of object. i.e A post with an array of shots

It is all working fine in the Apollo playground with this:

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

And this is my server schema:

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

Now this is my react mutation, the part I am stuck on. Because it is generating an error and I have no idea how to fix it. If I replace $shots with a static array of objects, it works! Do I need to use some fancy @relation tag or something?

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

This is how I am triggering the error:

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

And this is the error I can't shake

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

Regardless of this little hurdle, I gotta say that Apollo is the bees knees! Absolute awesomeness!!!


回答1:


I figured it out. I was so close the whole time!!!

All I was missing was an exclamation "!" at createPost()

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

Ouch that hurt! So many variables at play. Lesson learned!!!



来源:https://stackoverflow.com/questions/62113955/apollo-react-hooks-array-object-mutation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!