Reputation: 83
I've been following tutorials and trying to learn graphql with react and express and I'm running into trouble. My mutation works when I plug it into graphiql but not when I call it from my client.
Client code:
async addBook(params) {
var title = params["title"];
var author = params["author"];
var src = params["src"];
var mutation = `
{ addBook($author: String!, $title: String!, $src: String!) {
addBook(author: $author, title: $title, src: $src) {
id
title
}
}
}`;
const res = await fetch(this.apiUrl, {
method: 'POST',
mode: 'cors',
headers: new Headers({
'Content-Type': 'application/json',
'Accept': 'application/json',
}),
body: JSON.stringify({
query: mutation,
variables: {author: author, title: title, src: src}
}),
});
if (res.ok) {
const body = await res.json();
console.log(body.data);
return body.data;
} else {
throw new Error(res.status);
}
}
Schema code:
const typeDefs = `
type Book {
id: ID!
author: String!
title: String!
src: String!
}
type Query {
Books: [Book]
}
type Mutation {
addBook(author: String, title: String, src: String): Book
}
`;
Resolver
Mutation: {
addBook: (root, args) => {
const newBook = {id: Books.length+1, author: args.author, title: args.title, src: args.src};
Books.push(newBook);
return newBook;
},
},
The error
{"errors":[{"message":"Syntax Error GraphQL request (2:25) Expected Name, found $\n\n1: \n2: { mutation ($author: String!, $title: String!, $src: String!) {\n ^\n3: addBook(author: $author, title: $title, src: $src) {\n","locations":[{"line":2,"column":25}]}]}
My "database" is a .js file containing a const books
I can send queries and get results but mutations seem to be harder.
Any help would be greatly appreciated, thanks!
Upvotes: 2
Views: 628
Reputation: 20614
graphiql's probably being forgiving with your syntax, but it doesn't look quite correct to me. I would expect something like this:
var mutation = `
mutation AddBook($author: String!, $title: String!, $src: String!) {
addBook(author: $author, title: $title, src: $src) {
id
title
}
}
`;
Upvotes: 1