React Native, GraphQL, Apollo - how to create batch insert mutation

1.2k Views Asked by At

I need to create a batch insert mutation call in react native Here is my code. will you please solve my problem. I don't know where I have done a mistake. while onHandleSubmit data is not inserting in the table.

On submitting only am passing the array of object to the batch mutation call function.

 onHandleSubmit = () => {
      const TestResponse = [
{
        id:1,
        userId:123,
        testId:4321,
        itemId:43545,
        attempt:true,

},
{
        id:2,
        userId:123,
        testId:4321,
        itemId:43546,
        attempt:false,

}
];
      const { ResponseStudentTestTrack = [] } = this.props;
        ResponseStudentTestTrack(TestResponse);
  }

Appsync Shema:

type StudentTestTrack {
    id: ID!
    userId: ID!
    testId: ID!
    itemId: ID!
    attempt: String!
}

type StudentTestTrackConnection {
    items: [StudentTestTrack]
    nextToken: String
}

input CreateStudentTestTrackInput {
    id: ID!
    userId: ID!
    testId: ID!
    itemId: ID!
    attempt: String!
}

type Mutation { 
batchcreateStudentTestTrack(studentTest: [CreateStudentTestTrackInput]!): [StudentTestTrack]
}

Apollo call:

 graphql(CreateStudentTestTrack, {
    props: props => ({
      ResponseStudentTestTrack: TestResponse => props.mutate({
        variables: TestResponse,
        optimisticResponse: {
          __typename: 'Mutation',
          batchcreateStudentTestTrack: { ...TestResponse, __typename: 'CoursePatternStatus' },
        },
      }),
    }),
  }),

mutation :

export const CreateStudentTestTrack = gql`
mutation batchcreateStudentTestTrack{
  batchcreateStudentTestTrack(
    studentTest:[TestResponse]
  ) {
    id,
    userId,
    testId,
    itemId,
    attempt,
  }
}`;
1

There are 1 best solutions below

0
On BEST ANSWER

There seems to something wrong with client side mutation. Try this.

export const CreateStudentTestTrack = gql`
mutation abc ( // could be anyname
  $studentTest: [CreateStudentTestTrackInput] // Type of input mentioned in graphql definition
) {
  batchcreateStudentTestTrack(studentTest: $studentTest) {
    id,
    userId,
    testId,
    itemId,
    attempt,
  }
}`;

Also try removing optimistic response inside your graphql parameter if don't need to update ui cache and if your mutation call is just for insert. Also I have updated the mutate object based on my solutions. Please look into it too.

graphql(CreateStudentTestTrack, {
    props: props => ({
      ResponseStudentTestTrack: TestResponse => props.mutate({
        variables: {
          studentTest: TestResponse
        },
      }),
    }),
  }),

Also check you destructuring code.

const { ResponseStudentTestTrack } = this.props; // don't set default value as array for a function prop.

Try this code and you face issues comment below.