问题
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