leofontes
leofontes

Reputation: 927

React Native Apollo client GraphQL Mutation returns 400 error

I'm using GraphQL and Apollo on my React Native app, my queries are running fine, but when I try to run a mutation (that is working with the exact same code on the browser), I get the following error:

Error: Network error: Response not successful: Received status code 400
    at new ApolloError (bundle.umd.js:76)
    at bundle.umd.js:952
    at bundle.umd.js:1333
    at Array.forEach (<anonymous>)
    at bundle.umd.js:1332
    at Map.forEach (<anonymous>)
    at QueryManager.broadcastQueries (bundle.umd.js:1327)
    at bundle.umd.js:901
    at tryCallOne (core.js:37)
    at core.js:123

Here is how I'm trying to send this mutation:

const createItem = gql`{
  mutation {
    createItem(title: "Banana", summary: "Santa", campaignId: 1, pinId: 1) {
      id
    }
  }
}`;

client.query({query: createItem}).then((resp) => {
  console.log('query answer');
  console.log(resp);
}).catch((error) => {
  console.log('error');
  console.log(error);
});

And here's my client:

import { ApolloClient } from 'apollo-client';
import { HttpLink } from 'apollo-link-http';
import { setContext } from 'apollo-link-context';
import { InMemoryCache } from 'apollo-cache-inmemory';

let bearer_token = '';

const httpLink = new HttpLink({ uri: 'http://localhost:3000/graphql/' });

const authLink = setContext((_, { headers }) => {
  // get the authentication token from local storage if it exists
  const token = bearer_token;
  // return the headers to the context so httpLink can read them
  return {
    headers: {
      ...headers,
      authorization: token ? `Bearer ${bearer_token}` : "",
    }
  }
});

const client = new ApolloClient({
  link: authLink.concat(httpLink),
  cache: new InMemoryCache()
});

export function setToken(token) {
  bearer_token = token;
}

export default client;

On the backend, I debugged and the request is received, it finds the user based on the token that is setup on the client, but then does nothing and returns me a 400, again, only when I try to send it from the app, on the graphiql browser it works.

What am I missing? Thank you very much.

Upvotes: 1

Views: 1156

Answers (1)

leofontes
leofontes

Reputation: 927

As Daniel pointed, my gql had an extra bracket but that wasn't the problem, I actually should be using the mutate function instead of query. The documentation shows examples with query but I didn't find any with mutate, hence the confusion.

const createItem = gql`
mutation {
  createItem(title: "Banana", summary: "Santa", campaignId: 1, pinId: 1) {
    id
  }
}`;

And using it:

client.mutate({mutation: createItem}).then((resp) => {
  console.log(resp)
}).catch((error) => {
  console.log(error)
});

Hope this helps other GraphQL beginners!

Upvotes: 2

Related Questions