Jeremy
Jeremy

Reputation: 350

GraphQL + Apollo Error: Uncaught (in promise)

I'm trying to submit new data to my local graphQL API via button click but I'm getting an error: ERROR Error: Uncaught (in promise): Error: Network error: Http failure response for http://localhost:4000/graphql: 400 Bad Request.

the idea is that when you press the button new data gets submitted

  <button type="submit" (click)="onSubmit()" [disabled]="!personForm.valid" id="buttonSubmit" mat-raised-button color="accent"class="floated">Send</button>

onSubmit function calls mutation

  onSubmit() 
  {
    let id = 5;
    let vorname = 'user';
    let name =  'name';
    let email =  '[email protected]';
    let status =  'true';
    let activity =  'Office';

    this.apollo.mutate<CreateUserMutationResponse>({
      mutation: CREATE_USER_MUTATION,
      variables: {
        id: id,
        vorname: vorname,
        name: name,
        email: email,
        status: status,
        activity: activity
      }
    }).subscribe((response) => {

    });

    console.log('submitted');

  }

The mutation in my types.ts looks like this

export const CREATE_USER_MUTATION = gql`
  mutation CreateUserMutation($id: ID!, $vorname: String!, $name: String!, $email: String!, $status: String!, $activity: String) {
    createUser(id: $id,vorname: $vorname, name: $name, email: $email, status: $status, activity: $activity) {
      id
      vorname
      name
      email
      status
      activity
    }
  }
`;

export interface CreateUserMutationResponse {
  createUser: String;
}

Upvotes: 2

Views: 10775

Answers (1)

Adam G.
Adam G.

Reputation: 306

I actually had the same problem when I found your question. The documentation on this was hard to come by but, this example clued me in on how to fix this. It worked for me after I surrounded the mutation in a try catch statement. Something like this is what I am pretty sure will fix it for you too:

onSubmit() {

  [...]

  try {
    this.$apollo.mutate <CreateUserMutationResponse>({
      mutation: CREATE_USER_MUTATION,
      variables: {
        id: id,
        vorname: vorname,
        name: name,
        email: email,
        status: status,
        activity: activity
       }
     }).subscribe((response) => { });
   } catch (e) {
      console.error(e);
   }

  console.log('submitted');

This page also helped me out in setting up the mutation in the first place (which it seems you are already doing correctly).

Upvotes: 7

Related Questions